Skip to content

Markdown Code

Displaying code in Markdown is a very common scenario, whether it's technical documentation, tutorials, or code examples. This chapter will detail various uses of code in Markdown.

Inline Code

Basic Syntax

Use a single backtick ` to wrap code:

markdown
This is a paragraph containing `console.log()`.

Effect:

This is a paragraph containing console.log().

Multiple Phrases

markdown
Use the `git commit` command to commit code.
Use `const` and `let` to declare variables in JavaScript.

Effect:

Use the git commit command to commit code. Use const and let to declare variables in JavaScript.

Including Special Characters

Special characters within backticks don't need escaping:

markdown
Use `*` to represent multiplication.
HTML tags `<div>` are block-level elements.

Effect:

Use * to represent multiplication. HTML tags <div> are block-level elements.

Escaping Backticks

If the code itself contains backticks, use double backticks to wrap:

markdown
`` Use `code` to mark code ``

Effect:

Use code to mark code

Code Blocks

Basic Code Block

Use three backticks ``` to create a code block:

markdown

function hello() { console.log("Hello, World!"); }

Effect:

function hello() {
    console.log("Hello, World!");
}

Indented Code Block

Using 4 spaces or 1 tab for indentation can also create a code block:

markdown
    function hello() {
        console.log("Hello, World!");
    }

Effect:

function hello() {
    console.log("Hello, World!");
}

Syntax Highlighting

Specify Language

Add a language identifier after the three backticks to get syntax highlighting:

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

**Effect:**

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

Common Language Identifiers

LanguageIdentifier
JavaScriptjavascript or js
Pythonpython or py
Javajava
C/C++c or cpp
Gogo
Rustrust
Rubyruby
PHPphp
HTMLhtml
CSScss
SQLsql
Shell/Bashbash or sh
JSONjson
YAMLyaml
Markdownmarkdown or md

Various Language Examples

JavaScript

javascript
const greet = (name) => {
    return `Hello, ${name}!`;
};

console.log(greet("World"));

Python

python
class Person:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f"Hello, I'm {self.name}")

person = Person("Alice")
person.say_hello()

HTML

html
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <h1>Welcome</h1>
    <p>This is a paragraph.</p>
</body>
</html>

CSS

css
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
}

SQL

sql
SELECT
    id,
    name,
    email
FROM users
WHERE status = 'active'
ORDER BY created_at DESC;

JSON

json
{
    "name": "Zhang San",
    "age": 30,
    "skills": ["Python", "JavaScript", "Go"],
    "address": {
        "city": "Beijing",
        "district": "Chaoyang District"
    }
}

YAML

yaml
database:
  host: localhost
  port: 5432
  name: myapp

server:
  port: 8080
  mode: production

features:
  - auth
  - api
  - cache

Advanced Code Block Features

Line Numbers

Some editors support displaying line numbers:

markdown
```python {1,3-5}
def hello():
    print("First line")
    print("Second line")
    print("Third line")
    print("Fourth line")
    print("Fifth line")

**Effect:**

```python {1,3-5}
def hello():
    print("First line")
    print("Second line")
    print("Third line")
    print("Fourth line")
    print("Fifth line")

Code Block Title

markdown
```python title="greet.py"
def greet(name):
    print(f"Hello, {name}!")

### Collapsible Code Block

```markdown
```python fold
def long_function():
    # Lots of code
    pass

## Special Character Handling

### Escaping Backticks

In inline code, if the code contains backticks:

```markdown
Use `` `code` `` to mark code.

Effect:

Use `code` to mark code.

Use HTML Entities

markdown
Use &lt;div&gt; to create a div element.

Effect:

Use <div> to create a div element.

Code Block Best Practices

1. Always Specify Language

markdown
```python
def hello():
    print("Hello")

Specifying language gives syntax highlighting and better readability.

### 2. Keep Code Concise

Choose the most representative code snippets, avoid overly long code blocks.

### 3. Add Comments

```markdown
```python
# Calculate Fibonacci sequence
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

### 4. Use Consistent Indentation

Maintain consistent code indentation style.

### 5. Avoid Overly Long Lines

```markdown
```python
# Not recommended
result = some_long_function_name(argument1, argument2, argument3, argument4, argument5)

# Recommended
result = some_long_function_name(
    argument1,
    argument2,
    argument3
)

## Code Block Layout in Documents

### Between Paragraphs

```markdown
This is a paragraph.

```python
print("code block")

This is another paragraph.


### In Lists

```markdown
- Item 1
- Item 2 (contains code):

  ```python
  def hello():
      print("Hello")
  • Item 3

**Effect:**

- Item 1
- Item 2 (contains code):

  ```python
  def hello():
      print("Hello")
  • Item 3

In Blockquotes

markdown
> This is a blockquote:
>
> ```python
> print("code in quote")
> ```

Effect:

This is a blockquote:

python
print("code in quote")

Keyboard Shortcuts

Use HTML tags to display keyboard shortcuts:

html
<kbd>Ctrl</kbd> + <kbd>C</kbd>
<kbd>Cmd</kbd> + <kbd>S</kbd>
<kbd>Shift</kbd> + <kbd>Enter</kbd>

Effect:

Ctrl + CCmd + SShift + Enter

Code Block Export and Sharing

GitHub Gist

Share code as Gist, then embed in Markdown:

markdown
```js gist:1234567890

### External Links

```markdown
View complete code: [GitHub repository](https://github.com/username/repo)

Code Support on Different Platforms

GitHub/GitLab

  • Full syntax highlighting support
  • Supports multiple languages
  • Auto-detects language

Notion

  • Basic syntax highlighting
  • Supports common languages
  • Can copy code blocks

VS Code

  • Use plugins to preview Markdown
  • Full syntax highlighting
  • Supports custom themes

Typora

  • Real-time preview
  • Complete syntax highlighting
  • Switchable code themes

Practical Examples

Technical Documentation

markdown
## Install Dependencies

Use npm to install necessary packages:

```bash
npm install express mongoose cors

Configure Application

javascript
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World');
});

app.listen(3000);

### Code Comparison

```markdown
### Old Version

```javascript
function hello(name) {
    return "Hello " + name;
}

New Version

javascript
const hello = (name) => `Hello ${name}`;

## Summary

This chapter detailed code display methods in Markdown:

- **Inline code**: Use single backtick
- **Code blocks**: Use three backticks
- **Syntax highlighting**: Implemented through language identifiers
- **Advanced features**: Line numbers, titles, collapsing, etc.
- **Best practices**: Specify language, keep concise, add comments

Mastering code blocks will make your technical documentation more professional and readable.

**Next:** Learn how to use [Markdown Links](./links).

Content is for learning and research only.