Markdown: Markdown Code Syntax and Code Blocks

Code is the heart of technical documentation—Markdown provides an elegant way to present it so readers can both read and run it.

1. What You'll Learn


2. A Developer's Real Story

(1) Pain Point: Readers' Copied Code Throws Errors

Nina published Python tutorials on her tech blog, but readers complained that copying and running the code threw errors. Upon investigation, she found that her blogging platform's code blocks had no syntax highlighting—commas and periods looked identical, and some people copied ( as (full-width parentheses). Worse, some code blocks had no language label, so code appeared without any color differentiation.

(2) Solution: Standardize Code Block Formatting

Nina switched to fenced code blocks with proper language tags, and she tested every code snippet in a real environment before publishing. She also added a "Copy Code" button. After the switch, reader error reports dropped by 90%. Her blog gained recognition from multiple tech media outlets thanks to its highly reproducible code samples.


3. Inline Code

(1) Basic Syntax

Wrap text in a single backtick ` to create inline code:

MARKDOWN
Use the `print()` function to output text.

Run `npm install express` in the terminal.

The `<div>` tag is the most basic container in HTML.
Scenario Syntax Effect
Function name Call the `calculateTotal()` function Call the calculateTotal() function
Keyboard shortcut Press `Ctrl+S` to save Press Ctrl+S to save
Filename Edit the `.env` file Edit the .env file
Command Run `git status` Run git status

(2) Special Characters in Inline Code

To display a backtick itself, wrap it with double backticks:

MARKDOWN
Use `` ` `` to represent the backtick character.

In a sentence, use `code` and `` `backtick` `` together.
💡 Tip: Inline code is mainly for mentioning function names, variable names, file paths, keyboard shortcuts, and short commands. For longer code, use a code block.

▶ Example: Correct Usage of Inline Code

TEXT 📖 Display only
In the file utils/helpers.py, a format_date() function is defined.
Pass a datetime object to it and it returns a formatted string.

Press F5 to refresh the page.
💡 Tip: Text inside inline code stays as-is—even ** won't make it bold. This ensures the code is presented exactly as written.


4. Fenced Code Blocks

(1) Basic Syntax

Wrap a code block with triple backticks ``` and optionally specify a language tag for syntax highlighting:

MARKDOWN
```python
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
```
⚠️ Note: There must be blank lines before and after a code block, otherwise some parsers may fail to recognize it correctly. This is one of the most overlooked rules when writing documentation.

(2) The Role of Language Tags

Tag Language Example Filename
python Python main.py
javascript JavaScript app.js
html HTML index.html
css CSS style.css
bash Terminal Commands (none)
json JSON package.json
markdown Markdown README.md
text Plain Text Output (no highlighting)
PYTHON
# Python code with syntax highlighting
def fibonacci(n):
    """Compute the nth term of the Fibonacci sequence"""
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))  # Output: 55

5. Indented Code Blocks

Besides fenced code blocks, Markdown also supports indented code blocks. Indent each line by 4 spaces or 1 tab:

MARKDOWN
This is a paragraph.

    // 4-space indent turns this into a code block
    function hello() {
        console.log("Hello!");
    }

Back to normal text.
⚠️ Note: Indented code blocks do not support syntax highlighting and have no language tags. Always prefer fenced code blocks (```)—they are more powerful and clearer.

▶ Example: Fenced vs Indented Code Blocks

TEXT 📖 Display only
Fenced code blocks use triple backticks and support language tags and syntax highlighting.
Indented code blocks use 4 spaces at the start of a line, have good compatibility but no syntax highlighting.
Use fenced code blocks whenever possible.

6. Special Handling in Code Blocks

(1) Escaping Backticks in Code Blocks

If your code itself contains triple backticks, wrap it with more backticks:

MARKDOWN
````text
```python
print("Hello")
```
````
💡 Tip: The outer wrapper uses ```` (four backticks), so the inner ``` is displayed as plain text.

(2) Wrapping Long Lines of Code

MARKDOWN
# Recommended: keep each line within 80 characters
const result = await api.getUserData(userId)
  .then(data => processData(data))
  .catch(error => handleError(error));

# Avoid: unwrapped super-long lines
const result = await api.getUserData(userId).then(data => processData(data)).catch(error => handleError(error));

▶ Example: Common Error Markers in Code Blocks

TEXT 📖 Display only
❌ Wrong approach:
Code blocks without language tags show as black text on white background

✅ Right approach:
Code blocks with a python language tag display colorful syntax highlighting
⚠️ Note: Code blocks without language tags are ignored by syntax highlighters like Prism.js, displaying as black text on a white background—hard to read.


7. Embedding Code in Lists and Blockquotes

(1) Code Blocks inside Lists

Code blocks inside lists need an extra 8-space indent (or two tabs):

MARKDOWN
- Run the tests:

        npm test -- --coverage

- Check formatting:

        npx eslint src/ --fix
💡 Tip: You can also use fenced code blocks inside lists, but you need a blank line before and after the code block with consistent indentation.

(2) Code Blocks inside Blockquotes

MARKDOWN
> **Key implementation:**
>
> ```python
> def process_data(df):
>     return df.dropna().groupby("category").sum()
> ```
>
> The above code cleans null values and then groups and summarizes.

8. Complete Example: A Code Documentation Page

TEXT 📖 Display only
Data Processing Script Overview

Install dependencies: pip install pandas numpy matplotlib

load_data() function: loads data from a CSV file
clean_data() function: removes null values and duplicate rows

Full workflow:
1. Load data - load_data("sales.csv")
2. Clean - clean_data(data)
3. Output stats - print row count and column names

Expected result: A clean technical document with code and explanations alternating smoothly, correct language tags, and a clear division of labor between inline code and code blocks.


❓ FAQ

Q How to choose between inline code and code blocks?
A Use inline code for 2-3 words or fewer; use code blocks for anything longer than one line. Function names, variable names, filenames, and shortcuts go in inline code. Multi-line programs, configs, and commands go in code blocks.
Q Why isn't my code block showing syntax highlighting?
A The most common reason—missing language tag. Check if the code block opening line has a language name like python or javascript.
Q Can I use Markdown formatting inside a code block?
A No. Everything inside a code block is displayed as raw text. Asterisks won't become bold, hash signs won't become headings.
Q How do I display backticks inside a code block?
A Use more backticks for the outer wrapper. For example, to display three backticks, wrap with four backticks.
Q Will leading spaces in a code block be preserved?
A Yes. All indentation inside a code block is preserved exactly. This is intentional—Python, YAML, and other languages depend on indentation.

📖 Summary


📝 Exercises

  1. Basic: Write a Markdown section that includes 3 inline code snippets (filename, function name, keyboard shortcut) and 1 code block with a language tag.

  2. Intermediate: Create a nested structure in your Markdown document—embed a code block inside an unordered list item, and embed a code block inside a blockquote.

  3. Challenge: Write a Markdown section with three levels of backtick nesting (demonstrating how to show a code block that itself shows a code block), and use four backticks for the outer wrapper to ensure correct rendering.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏