Markdown 是开发者文档的通用语言。无论你在编写 GitHub README、项目 Wiki 还是 Pull Request 描述,掌握 Markdown 语法都能让你在几分钟内创建专业、可读的文档。本速查表涵盖了 GitHub 支持的每一个 Markdown 功能——从基本格式到 Mermaid 图表、数学公式和可折叠区域。
1. 基础语法:标题、粗体、斜体、链接、图片
这些是你在每个文档中都会用到的基础 Markdown 元素。它们在 GitHub、GitLab、Bitbucket 和大多数 Markdown 渲染器中的表现完全一致。
Headings
源码:
# Heading 1
## Heading 2
### Heading 3
#### Heading 4
##### Heading 5
###### Heading 6渲染效果: Six levels of headings, from largest (H1) to smallest (H6). Use only one H1 per document (typically your project name).
Bold & Italic
源码:
**bold text**
__also bold__
*italic text*
_also italic_
***bold and italic***
___also bold and italic___
~~strikethrough~~渲染效果: bold text, italic text, bold and italic, and strikethrough.
Links
源码:
[Link text](https://example.com)
[Link with title](https://example.com "Hover title text")
[Relative link](./docs/guide.md)
[Reference-style link][ref-id]
[Section anchor link](#section-name)
<!-- Reference definition (placed anywhere in the doc) -->
[ref-id]: https://example.com "Optional title"渲染效果: Clickable hyperlinks. Reference-style links let you define URLs once and reuse them. Anchor links jump to headings within the same page.
Images
源码:


<!-- Sized image using HTML -->
<img src="https://example.com/logo.png" alt="Logo" width="200">
<!-- Centered image -->
<p align="center">
<img src="./banner.png" alt="Banner" width="600">
</p>
<!-- Image as a link -->
[](https://example.com)渲染效果: Inline images. Use HTML <img> when you need to control width, height, or alignment. Wrap an image in a link to make it clickable.
Lists
源码:
<!-- Unordered list -->
- Item one
- Item two
- Nested item
- Another nested
- Item three
<!-- Ordered list -->
1. First step
2. Second step
3. Third step
1. Sub-step A
2. Sub-step B
<!-- Mixed -->
1. Main item
- Detail A
- Detail B
2. Next item渲染效果: Bulleted and numbered lists. Indent with 2-4 spaces to create nested levels. You can mix ordered and unordered lists.
Blockquotes
源码:
> This is a blockquote.
> It can span multiple lines.
>
> > Nested blockquotes work too.渲染效果: Indented text blocks with a left border, commonly used for quoting text or adding contextual notes.
Horizontal Rules
源码:
---
***
___渲染效果: A horizontal divider line. All three syntaxes produce identical output. Use them to separate major sections.
Inline Code
源码:
Use `npm install` to install dependencies.
To escape backticks inside inline code, use double backticks:
``Use `code` here``渲染效果: Monospaced text like npm install. Perfect for referencing commands, variables, filenames, and short code snippets within paragraphs.
2. GitHub 风格 Markdown(GFM)
GitHub 通过称为 GitHub Flavored Markdown 的附加功能扩展了标准 Markdown。包括任务列表、删除线文本、自动链接等。
Task Lists (Checkboxes)
源码:
- [x] Design the database schema
- [x] Implement REST API endpoints
- [ ] Write unit tests
- [ ] Deploy to production
- [ ] Update documentation渲染效果: Interactive checkboxes. Checked items show a filled checkbox, unchecked items show an empty one. In GitHub Issues and PRs, these are clickable to toggle state.
Strikethrough
源码:
~~This text is struck through~~
~~Deprecated: Use newFunction() instead~~渲染效果: This text is struck through. Useful for marking deprecated information or crossed-out items.
Autolinks
源码:
https://github.com
user@example.com
#123 (links to issue/PR #123)
@username (mentions a GitHub user)
SHA: a1b2c3d (links to a commit if valid)渲染效果: GitHub automatically converts URLs, email addresses, issue numbers, @mentions, and commit SHAs into clickable links. No special syntax needed.
Footnotes
源码:
This claim needs a source[^1]. Another reference here[^note].
[^1]: Source: https://example.com/research
[^note]: This is a longer footnote with multiple paragraphs.
Indent subsequent paragraphs with 4 spaces.渲染效果: Superscript numbers that link to footnote definitions at the bottom of the page. Great for citations and additional context without cluttering the main text.
3. 表格:语法、对齐、多行单元格
Markdown 表格对于文档化 API、配置选项和比较矩阵至关重要。GitHub 支持列对齐和复杂的表格结构。
Basic Table
源码:
| Feature | Free Plan | Pro Plan | Enterprise |
|---------------|-----------|----------|------------|
| Users | 5 | 50 | Unlimited |
| Storage | 1 GB | 100 GB | 1 TB |
| Support | Community | Email | 24/7 Phone |
| Custom domain | No | Yes | Yes |渲染效果: A formatted table with a header row and data rows. Columns are separated by pipes (|) and the header is separated from data by a row of dashes.
Column Alignment
源码:
| Left-aligned | Center-aligned | Right-aligned |
|:-------------|:--------------:|--------------:|
| Left | Center | Right |
| Text | Text | Text |
| Data | Data | Data |渲染效果: Columns aligned left (default), center, or right. Add colons to the separator row: :--- for left, :---: for center, ---: for right.
Tables with Formatting
源码:
| Method | Endpoint | Description |
|----------|-------------------|--------------------------|
| `GET` | `/api/users` | **List** all users |
| `POST` | `/api/users` | **Create** a new user |
| `GET` | `/api/users/:id` | Get user by *ID* |
| `PUT` | `/api/users/:id` | **Update** user |
| `DELETE` | `/api/users/:id` | ~~Remove~~ **Delete** user |渲染效果: Tables support inline formatting inside cells -- bold, italic, code, strikethrough, and links all work inside table cells.
Multi-Line Cells (HTML)
源码:
<table>
<tr>
<th>Command</th>
<th>Description</th>
</tr>
<tr>
<td>
```bash
npm install
```
</td>
<td>
Install all dependencies from **package.json**.
Runs `preinstall` and `postinstall` scripts.
</td>
</tr>
<tr>
<td>
```bash
npm run build
```
</td>
<td>
Build the project for production.
Output goes to the `dist/` directory.
</td>
</tr>
</table>渲染效果: HTML tables allow multi-line content, code blocks, and complex formatting inside cells that pure Markdown tables cannot handle.
4. 代码块:语言提示和 Diff 语法高亮
代码块可以说是开发者文档中最重要的功能。GitHub 支持数百种语言的语法高亮,以及用于显示更改的特殊 diff 格式。
Fenced Code Blocks with Language
源码:
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('World'));
```
```python
def greet(name: str) -> str:
return f"Hello, {name}!"
print(greet("World"))
```
```bash
#!/bin/bash
echo "Installing dependencies..."
npm install
npm run build
```渲染效果: Syntax-highlighted code blocks. Add the language identifier after the opening triple backticks. GitHub supports 200+ languages including javascript, python, bash, typescript, go, rust, java, c, cpp, csharp, ruby, php, swift, kotlin, sql, yaml, json, html, css, and more.
Diff Syntax Highlighting
源码:
```diff
- const API_URL = 'http://localhost:3000';
+ const API_URL = process.env.API_URL || 'https://api.example.com';
function fetchData() {
- return fetch(API_URL + '/data');
+ return fetch(API_URL + '/v2/data', {
+ headers: { 'Authorization': 'Bearer ' + token }
+ });
}
```渲染效果: Lines starting with - are highlighted in red (removed), lines starting with + are highlighted in green (added), and unchanged lines have no highlight. Perfect for showing code changes in documentation.
Code Block with Filename
源码:
> **`src/config.ts`**
```typescript
export const config = {
port: parseInt(process.env.PORT || '3000'),
database: process.env.DATABASE_URL,
redis: process.env.REDIS_URL,
};
```渲染效果: While Markdown does not natively support filenames on code blocks, you can use a bold inline code heading right above the block to simulate this common pattern.
5. 徽章:shields.io 语法和常用徽章
徽章提供一目了然的项目状态信息。它们由 shields.io 驱动,是专业 README 文件的标配。
shields.io Basic Syntax
源码:
<!-- Static badge -->

<!-- Examples -->




<!-- Badge with logo -->


渲染效果: Colored badges with labels, messages, and optional logos. The format is https://img.shields.io/badge/LABEL-MESSAGE-COLOR. Common colors: brightgreen, green, yellow, orange, red, blue, lightgrey.
Common Dynamic Badges
源码:
<!-- npm version -->

<!-- npm downloads -->

<!-- GitHub stars -->

<!-- GitHub issues -->

<!-- GitHub license -->

<!-- Build status (GitHub Actions) -->

<!-- Code coverage -->

<!-- Bundle size -->
渲染效果: Dynamic badges that automatically update based on live data from npm, GitHub, Codecov, and other services. Replace owner/repo and package-name with your actual values.
Badge Layout in README
源码:
<!-- Badges on same line -->
  
<!-- Centered badges -->
<p align="center">
<a href="https://npmjs.com/package/my-lib"><img src="https://img.shields.io/npm/v/my-lib" alt="npm version"></a>
<a href="https://github.com/me/my-lib/blob/main/LICENSE"><img src="https://img.shields.io/github/license/me/my-lib" alt="license"></a>
<a href="https://github.com/me/my-lib/actions"><img src="https://img.shields.io/github/actions/workflow/status/me/my-lib/ci.yml" alt="build status"></a>
</p>渲染效果: Badges arranged horizontally. Use HTML for centered badges or to make badges clickable links. Place badges right below your project title for maximum visibility.
6. 可折叠区域:details/summary HTML
可折叠区域通过将冗长内容隐藏在可点击的切换按钮后面来保持 README 整洁。GitHub 原生渲染 <details> 和 <summary> HTML 元素。
Basic Collapsible
源码:
<details>
<summary>Click to expand</summary>
This content is hidden by default.
You can put **any Markdown** here:
- Lists
- Code blocks
- Tables
- Images
```javascript
console.log('Hidden code example');
```
</details>渲染效果: A clickable triangle/arrow with the summary text. Clicking it reveals the hidden content. The content supports full Markdown formatting.
Open by Default
源码:
<details open>
<summary>Expanded by default</summary>
This content is visible when the page loads.
Users can click to collapse it.
</details>渲染效果: Same as above, but the section starts expanded. Add the open attribute to the <details> tag.
Nested Collapsibles & Practical Examples
源码:
<details>
<summary><strong>Environment Variables</strong></summary>
| Variable | Required | Default | Description |
|-----------------|----------|-------------|-----------------------|
| `DATABASE_URL` | Yes | - | PostgreSQL connection |
| `REDIS_URL` | No | localhost | Redis connection |
| `PORT` | No | 3000 | Server port |
| `NODE_ENV` | No | development | Environment mode |
</details>
<details>
<summary><strong>Full Changelog</strong></summary>
### v2.0.0 (2025-01-15)
- Breaking: Renamed `config.js` to `config.ts`
- Added TypeScript support
- Removed deprecated `legacyMode` option
### v1.5.0 (2024-12-01)
- Added Redis caching
- Fixed memory leak in WebSocket handler
- Updated dependencies
</details>渲染效果: Collapsible sections with rich content like tables and changelogs. Use bold text in the summary for emphasis. This pattern is ideal for environment variable docs, changelogs, and verbose configuration details.
7. 警告提示:[!NOTE]、[!TIP]、[!WARNING]、[!CAUTION]
GitHub 支持基于引用块的特殊警告提示,会以彩色图标渲染。非常适合突出显示重要信息、提示、警告和破坏性更改。
All Alert Types
源码:
> [!NOTE]
> Useful information that users should know,
> even when skimming content.
> [!TIP]
> Helpful advice for doing things better
> or more easily.
> [!IMPORTANT]
> Key information users need to know to
> achieve their goal.
> [!WARNING]
> Urgent info that needs immediate user
> attention to avoid problems.
> [!CAUTION]
> Advises about risks or negative outcomes
> of certain actions.渲染效果: Five styled callout boxes with distinct colors and icons. NOTE is blue, TIP is green, IMPORTANT is purple, WARNING is yellow, and CAUTION is red. These only work on GitHub (not all Markdown renderers).
Alerts with Rich Content
源码:
> [!WARNING]
> **Breaking Change in v3.0**
>
> The `config.legacy` option has been removed.
> Migrate to the new format:
>
> ```diff
> - legacy: true
> + mode: 'modern'
> ```
>
> See the [Migration Guide](./MIGRATION.md) for details.渲染效果: Alerts can contain bold text, code blocks, links, and other Markdown formatting. They are ideal for migration notices and deprecation warnings in README files.
8. Mermaid 图表:流程图、时序图、甘特图
GitHub 原生在围栏代码块中渲染 Mermaid 图表。你可以创建流程图、时序图、甘特图等,无需任何外部工具。
Flowchart
源码:
```mermaid
flowchart TD
A[Start] --> B{Is authenticated?}
B -->|Yes| C[Show Dashboard]
B -->|No| D[Show Login Page]
D --> E[Enter Credentials]
E --> F{Valid?}
F -->|Yes| C
F -->|No| G[Show Error]
G --> D
C --> H[End]
```渲染效果: A visual flowchart with boxes, diamonds (decision points), and arrows. TD means top-down direction. Use LR for left-to-right. Node shapes: [rectangular], {diamond}, (rounded), ([stadium]).
Sequence Diagram
源码:
```mermaid
sequenceDiagram
participant Client
participant API
participant Auth
participant DB
Client->>API: POST /login {email, password}
API->>Auth: Validate credentials
Auth->>DB: Query user
DB-->>Auth: User record
Auth-->>API: JWT token
API-->>Client: 200 OK {token}
Client->>API: GET /data (Bearer token)
API->>Auth: Verify token
Auth-->>API: Valid
API->>DB: SELECT * FROM data
DB-->>API: Results
API-->>Client: 200 OK {data}
```渲染效果: A sequence diagram showing interactions between participants over time. Solid arrows (->>) represent requests, dashed arrows (-->>) represent responses. Perfect for documenting API flows and authentication sequences.
Gantt Chart
源码:
```mermaid
gantt
title Project Roadmap Q1 2025
dateFormat YYYY-MM-DD
section Backend
API Design :a1, 2025-01-01, 14d
Implementation :a2, after a1, 21d
Testing :a3, after a2, 7d
section Frontend
UI Mockups :b1, 2025-01-01, 7d
Component Development:b2, after b1, 28d
Integration :b3, after a2, 14d
section DevOps
CI/CD Pipeline :c1, 2025-01-15, 7d
Staging Deploy :c2, after a3, 3d
Production Deploy :milestone, after b3, 0d
```渲染效果: A Gantt chart with tasks, durations, dependencies, and milestones. Sections group related tasks. Use after taskId to define dependencies between tasks.
Other Mermaid Diagrams
源码:
<!-- Class Diagram -->
```mermaid
classDiagram
class User {
+String name
+String email
+login()
+logout()
}
class Admin {
+deleteUser()
+banUser()
}
User <|-- Admin
```
<!-- Pie Chart -->
```mermaid
pie title Language Distribution
"TypeScript" : 45
"Python" : 25
"Go" : 15
"Rust" : 10
"Other" : 5
```渲染效果: Mermaid also supports class diagrams, pie charts, entity-relationship diagrams, state diagrams, and more. Check the Mermaid documentation for the full list of supported diagram types.
9. 数学公式:$行内$ 和 $$块级$$
GitHub 支持使用美元符号分隔符的 LaTeX 数学表达式。单个美元符号用于行内数学,双美元符号用于块级公式。
Inline Math
源码:
The quadratic formula is $x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$ where $a \neq 0$.
Einstein's famous equation: $E = mc^2$
The time complexity is $O(n \log n)$ in the average case.渲染效果: Mathematical expressions rendered inline within a paragraph of text. Single dollar signs delimit inline math. The expressions render as properly formatted mathematical notation with fractions, square roots, superscripts, and symbols.
Block Math
源码:
$$
\sum_{i=1}^{n} i = \frac{n(n+1)}{2}
$$
$$
\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
$$
$$
\begin{bmatrix}
a & b \\
c & d
\end{bmatrix}
\times
\begin{bmatrix}
e \\
f
\end{bmatrix}
=
\begin{bmatrix}
ae + bf \\
ce + df
\end{bmatrix}
$$渲染效果: Centered, display-mode math equations. Double dollar signs create block-level equations. Supports summation notation, integrals, matrices, and virtually any LaTeX math expression. Equations appear on their own line and are centered.
Math in Code Blocks (Alternative)
源码:
```math
\left( \sum_{k=1}^n a_k b_k \right)^2
\leq
\left( \sum_{k=1}^n a_k^2 \right)
\left( \sum_{k=1}^n b_k^2 \right)
```渲染效果: An alternative syntax using a fenced code block with the math language identifier. This is useful when dollar-sign delimiters conflict with currency symbols in your document.
10. 表情符号::emoji_name: 短代码
GitHub 支持表情短代码,在 Markdown 文件、Issue 和 Pull Request 中渲染为表情符号,为文档增添视觉趣味。
Common Emoji Shortcodes
源码:
<!-- Status & Feedback -->
:white_check_mark: :x: :warning: :bulb: :memo:
<!-- Reactions -->
:+1: :-1: :heart: :star: :fire: :rocket:
<!-- Development -->
:bug: :wrench: :hammer: :gear: :package: :lock:
<!-- People & Gestures -->
:wave: :clap: :muscle: :eyes: :tada:
<!-- Arrows & Symbols -->
:arrow_right: :arrow_left: :arrow_up: :arrow_down:
:heavy_check_mark: :heavy_multiplication_x:
:information_source: :link:渲染效果: Emoji icons corresponding to each shortcode. For example, :rocket: renders as a rocket icon, :bug: renders as a bug icon. GitHub supports hundreds of emoji shortcodes. You can also paste Unicode emoji directly.
Emoji in Context
源码:
## :rocket: Quick Start
### :package: Installation
```bash
npm install my-awesome-lib
```
### :gear: Configuration
See [config docs](./CONFIG.md).
### :bug: Known Issues
- :warning: Memory leak in v2.1 (fixed in v2.2)
- :white_check_mark: All tests passing
### :heart: Contributing
PRs welcome! :tada:渲染效果: Emoji used as section icons in headings and inline markers for status. This is a popular pattern in open-source README files to make sections visually scannable.
11. README 模板
一个结构良好的 README 是你项目的门面。这里有一个完整的模板,你可以复制并为任何仓库自定义。
<p align="center">
<img src="./assets/logo.png" alt="Project Logo" width="120">
</p>
<h1 align="center">Project Name</h1>
<p align="center">
<strong>One-line description of what your project does.</strong>
</p>
<p align="center">
<a href="https://npmjs.com/package/your-pkg"><img src="https://img.shields.io/npm/v/your-pkg" alt="npm"></a>
<a href="https://github.com/you/repo/actions"><img src="https://img.shields.io/github/actions/workflow/status/you/repo/ci.yml" alt="build"></a>
<a href="https://github.com/you/repo/blob/main/LICENSE"><img src="https://img.shields.io/github/license/you/repo" alt="license"></a>
</p>
---
## :sparkles: Features
- **Feature 1** -- Brief description
- **Feature 2** -- Brief description
- **Feature 3** -- Brief description
## :package: Installation
```bash
# npm
npm install project-name
# yarn
yarn add project-name
# pnpm
pnpm add project-name
```
## :rocket: Quick Start
```typescript
import { something } from 'project-name';
const result = something({
option1: 'value',
option2: true,
});
console.log(result);
```
## :book: API Reference
### `something(options)`
| Parameter | Type | Default | Description |
|-----------|-----------|---------|-----------------------|
| option1 | `string` | `-` | Required. Main input |
| option2 | `boolean` | `false` | Enable advanced mode |
| option3 | `number` | `10` | Max retry count |
**Returns:** `Promise<Result>`
<details>
<summary><strong>Full Options Reference</strong></summary>
| Parameter | Type | Default | Description |
|-----------|----------|--------------|--------------------------|
| timeout | `number` | `5000` | Request timeout (ms) |
| retries | `number` | `3` | Number of retry attempts |
| baseURL | `string` | `'/api'` | API base URL |
| headers | `object` | `{}` | Custom request headers |
</details>
## :wrench: Configuration
<details>
<summary><strong>Environment Variables</strong></summary>
| Variable | Required | Default | Description |
|---------------|----------|-------------|----------------------|
| `API_KEY` | Yes | - | Your API key |
| `DEBUG` | No | `false` | Enable debug logging |
| `PORT` | No | `3000` | Server port |
</details>
## :test_tube: Running Tests
```bash
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run specific test file
npm test -- --grep "feature"
```
## :handshake: Contributing
Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) before submitting a PR.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## :scroll: License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
<p align="center">
Made with :heart: by <a href="https://github.com/yourname">Your Name</a>
</p>渲染效果: A complete, professional README with logo, badges, features, installation instructions, API reference, configuration, test commands, contributing guide, and license section. Copy this template and replace the placeholder values with your project details.
12. 常见问题
Markdown 和 GitHub Flavored Markdown(GFM)有什么区别?
标准 Markdown(CommonMark)定义了标题、粗体、斜体、链接和图片等核心语法。GitHub Flavored Markdown 在此基础上扩展了任务列表、表格、删除线、自动链接、警告提示、Mermaid 图表和数学公式。GFM 是一个超集——所有标准 Markdown 在 GFM 中都能工作,但 GFM 功能在其他平台上可能无法渲染。
如何在 GitHub README 中添加目录?
GitHub 会自动在任何包含多个标题的 Markdown 文件左上角生成目录图标。要手动创建目录,使用锚点语法创建链接列表:[章节名称](#section-name)。GitHub 通过将标题文本转为小写并用连字符替换空格来自动生成锚点。
可以在 GitHub Markdown 中使用 HTML 吗?
可以,GitHub 在 Markdown 文件中支持 HTML 的一个子集。常用元素包括用于可折叠区域的 <details>/<summary>、带 width/height 属性的 <img>、用于换行的 <br>、用于键盘按键的 <kbd>、用于上下标的 <sub>/<sup>。但出于安全考虑,<script>、<style> 和大多数事件处理属性会被过滤。
如何在 README 中并排显示图片?
使用无边框的 HTML 表格:<table><tr><td><img src="img1.png" width="300"></td><td><img src="img2.png" width="300"></td></tr></table>。也可以使用 HTML <p align="center"> 包装器配合多个 <img> 标签。标准 Markdown 本身不支持并排图片。
为什么我的 Markdown 换行在 GitHub 上不显示?
在 Markdown 中,行与行之间的单个换行符被视为空格而非换行。要创建换行(软回车),在按 Enter 前在行尾添加两个空格,或使用 HTML <br> 标签。要创建新段落,在文本块之间留一个空行。这是初学者最常遇到的 Markdown 陷阱之一。
收藏这份速查表,在编写 GitHub 文档时随时查阅。掌握这些技巧,你的 README 文件将清晰、专业且信息丰富。