Markdown Code Formatting: The Complete Guide
Markdown Code Formatting: The Complete Guide
Markdown code formatting is one of the most frequently used features in technical writing, documentation, README files, and blog posts. Getting it right makes your content readable, scannable, and professional. Getting it wrong means walls of monospaced text with no context, or worse, code that readers cannot easily copy and run.
This guide covers every code formatting pattern in markdown, from the simplest inline snippet to diff blocks and language-specific syntax highlighting.
Quick Answer: Markdown code formatting uses backticks for inline code and triple backticks (fenced blocks) for multi-line samples. Adding a language identifier (e.g., ```javascript) enables syntax highlighting across GitHub, VS Code, and most renderers. Over 100 languages are supported. Diff blocks use + and - to show additions and removals.
What Is Inline Code and When Should You Use It?
Inline code is for short references that appear within a sentence: function names, variable names, command flags, file paths, or short values.
Syntax: wrap the text in single backticks.
Use `npm install` to add a package.
The `config.json` file controls the settings.
Set the value to `true` to enable the feature.
Renders as:
Use npm install to add a package.
The config.json file controls the settings.
Set the value to true to enable the feature.
When to Use Inline Code
- Command names:
git,curl,ls - File names and paths:
src/index.ts,.env - Variable and function names:
getUserById(),maxRetries - Key names in configuration:
"port","host" - Short values:
null,undefined,200
Do not use inline code for entire code samples. If it is more than one line or needs to be copied and run, use a fenced code block instead.
How Do Fenced Code Blocks Work?
Fenced code blocks are the standard for multi-line code samples. They preserve whitespace, display in monospace font, and are easy to copy.
Syntax: three backticks before and after the code block.
```
function greet(name) {
return `Hello, ${name}!`;
}
```
Renders as:
function greet(name) {
return `Hello, ${name}!`;
}
Language Identifiers for Syntax Highlighting
Add a language identifier immediately after the opening triple backticks to enable syntax highlighting. This is a critical detail that many writers skip.
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
```
The language identifier tells the renderer which grammar to use for coloring keywords, strings, comments, and operators.
What Are the Common Language Identifiers?
Here is a reference list of the most commonly used language identifiers:
| Language | Identifier |
|---|---|
| JavaScript | javascript or js |
| TypeScript | typescript or ts |
| Python | python or py |
| Bash/Shell | bash or sh |
| HTML | html |
| CSS | css |
| JSON | json |
| YAML | yaml or yml |
| SQL | sql |
| Markdown | markdown or md |
| Rust | rust |
| Go | go |
| Java | java |
| C | c |
| C++ | cpp |
| C# | csharp |
| Ruby | ruby |
| PHP | php |
| Swift | swift |
| Kotlin | kotlin |
| Dockerfile | dockerfile |
| TOML | toml |
| XML | xml |
| GraphQL | graphql |
Most markdown renderers (GitHub, VS Code, edtr.md, Pandoc) recognize all of these identifiers. Highlight.js, the library used by many renderers including edtr.md, supports over 190 programming languages out of the box.
Syntax Highlighting Examples
A few practical examples showing language identifiers in use:
TypeScript
type User = {
id: number;
name: string;
email: string;
};
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
Bash
#!/bin/bash
set -e
echo "Deploying application..."
git pull origin main
npm ci
npm run build
pm2 restart app
echo "Done."
SQL
SELECT
u.id,
u.name,
COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id, u.name
ORDER BY order_count DESC
LIMIT 10;
JSON
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build"
},
"dependencies": {
"next": "^15.0.0",
"react": "^19.0.0"
}
}
How Do Diff Blocks Show Code Changes?
Diff blocks show what changed between two versions of code. They are invaluable in documentation, pull request descriptions, and tutorials that walk through code changes.
The language identifier is diff. Lines starting with + highlight as additions, lines starting with - highlight as removals.
```diff
- const greeting = "Hello World";
+ const greeting = `Hello, ${name}!`;
```
This renders with green additions and red deletions in most renderers.
For GitHub specifically, you can also use diff blocks in PR descriptions to show migration steps or configuration changes:
```diff
// package.json
- "tailwindcss": "^3.4.0"
+ "tailwindcss": "^4.0.0"
```
Indented Code Blocks (Legacy Syntax)
The original markdown specification also supports code blocks using four-space indentation. This predates fenced code blocks.
function legacy() {
console.log("indented code block");
}
You should avoid this syntax today. It does not support language identifiers, it is visually ambiguous (is that indentation meaningful or just formatting?), and it conflicts with lists inside blockquotes. Fenced code blocks are universally supported and unambiguous.
How Do You Nest Code Blocks in Documentation?
If you need to show markdown syntax that contains code blocks (for example, in a guide like this one), use four backticks for the outer fence:
````
```javascript
const x = 1;
```
````
This is useful for documentation, tutorials, and any content that teaches markdown itself.
Tips for Readable Code Blocks
1. Always add a language identifier.
Unhighlighted code is harder to scan. Even if syntax highlighting looks similar in your preview, it is meaningful to screen readers and automated tools.
2. Keep code blocks focused.
Show only the relevant portion. If you are explaining a single function, do not include an entire file. Use // ... or # ... to indicate omitted context:
// ... existing imports
function handleSubmit(event) {
event.preventDefault();
// ... validation logic
submitForm(data);
}
3. Use comments to annotate.
# Read the config file
with open("config.json") as f:
config = json.load(f)
# Validate required keys
required = ["host", "port", "database"]
for key in required:
assert key in config, f"Missing config key: {key}"
4. Align multi-line strings and arguments for readability.
curl -X POST https://api.example.com/data \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"key": "value"}'
5. Do not paste minified code.
If the source code is minified, de-minify it before including it in documentation. Readable code in examples is the point.
How Does Code Formatting Work in GitHub?
GitHub renders markdown with syntax highlighting across issues, pull requests, README files, and wikis. The same fenced code block syntax works everywhere. GitHub also supports the diff identifier in PR descriptions for showing before/after changes.
For a broader reference on markdown in GitHub contexts, see the markdown for GitHub guide.
What Makes Code Formatting Work in Technical Documentation?
When writing technical documentation, consistent code formatting helps readers trust your content. If some code examples have syntax highlighting and some do not, or if inline code is used inconsistently, the documentation feels unpolished.
A simple rule: anything that a reader might copy and use verbatim belongs in a code format. Everything else is prose.
For broader technical documentation patterns, see technical documentation with markdown. If you need a concise syntax reference to keep nearby while writing, the markdown cheat sheet covers all core formatting elements in one place.
Practice Markdown Code Formatting Now
Open edtr.md and paste a code sample into the editor. Try different language identifiers and watch the syntax highlighting update in real time. The live preview makes it easy to verify your formatting before publishing to documentation, GitHub, or any other platform.
Try it yourself
Open edtr.md and start writing Markdown with live preview, diagrams, math, and PDF export. Free, no sign-up.
Open editor