Two Ways to Show Code
Markdown gives you two syntaxes for showing code, and the difference is about scope: inline code (single backticks) marks a short snippet inside a sentence, while a code block (a fence of three backticks) sets multiple lines apart as their own block — and only fenced code blocks accept a language identifier for syntax highlighting. Reach for inline code when you name an identifier while writing prose (print(), user_count, config.json); reach for a code block when you are showing something meant to be read or copied whole — a function, a config file, a terminal session.
That is the summary an AI Overview will give you. What it can't hand you is the decision at the point of writing: which syntax fits this snippet, why your fenced block shows up grey and un-highlighted, and how to display a literal backtick when the code you're documenting is itself Markdown. The table, diagram, and worked examples below cover exactly those edges.
Inline Code vs Code Blocks vs Indented Blocks at a Glance
Three syntaxes, three jobs. This is the fast reference — the rest of the article expands each row with examples.
| Feature | Inline code | Fenced code block | Indented code block |
|---|---|---|---|
| Syntax | Single backticks: `code` | Three backticks (or ~~~) on lines before/after | Indent every line 4 spaces / 1 tab |
| Spans | One line, mid-sentence | Multiple lines, standalone | Multiple lines, standalone |
| Language hint | No | Yes — first word after the fence | No |
| Syntax highlighting | Never | Yes, when a language is set | Never |
| Best for | Function names, variables, filenames, flags, keys | Full functions, config files, commands + output | Legacy docs / pre-GFM renderers only |
| Copy-friendly | Reads as part of the text | Rendered as a distinct, copyable block | Distinct block, but easy to break |
| When to use | Snippet is 1–5 words and lives in a sentence | Code is multi-line or you want a highlighted, copyable example | Almost never — prefer fenced blocks |
The diagram below shows the same principle as a decision: how many lines, and does it need highlighting?
Understanding when to use each—and how to maximize their effectiveness—is essential for clear technical documentation. The wrong choice creates confusion and breaks reading flow; the right choice makes complex technical concepts accessible and scannable.
Inline Code: Code Within Text
Inline code uses single backticks (`) to mark code within regular paragraphs, preserving its literal formatting while maintaining text flow.
Basic Syntax
Use the `print()` function to output text in Python.
The variable `user_count` stores the number of active users.
Run `npm install` to install dependencies.
Renders as: Use the print() function to output text in Python.
When to Use Inline Code
Function and Method Names: Mark function calls to distinguish them from prose:
Call `authenticate()` before calling `fetchUserData()`.
Variable Names: Identify variables referenced in explanations:
The `max_connections` variable limits concurrent database connections.
Short Commands: Indicate terminal commands within instructions:
Run `git status` to check your repository state.
File and Directory Names: Clarify paths and filenames:
Edit the `config.json` file in the `/etc/app/` directory.
Parameter Names: Reference parameters in API documentation:
The `timeout` parameter controls request duration in seconds.
Keywords and Operators: Highlight programming language keywords:
Use the `async` keyword before function declarations.
Configuration Keys: Identify configuration options:
Set `debug: true` in your settings.
Best Practices for Inline Code
Don't Overuse: Not every technical term needs backticks. "We're using React" doesn't require React in code formatting—it's clear from context. Reserve inline code for identifiers that benefit from literal formatting.
Maintain Readability: Excessive inline code makes paragraphs choppy. This is hard to read:
The `function` `getUserData()` calls the `API` endpoint `/api/users` with the `userId` parameter.
Better:
The getUserData() function calls the `/api/users` endpoint with a userId parameter.
Be Consistent: If you mark one function name with inline code, mark all function names consistently throughout your documentation.
Include Syntax When Helpful: For functions, include parentheses: getData() not getData. For methods with parameters, consider showing them: fetch(url, options).
Code Blocks: Standalone Code Examples
Code blocks display multiple lines of code as distinct, formatted sections separate from surrounding text.
Fenced Code Block Syntax
Use three backticks (```) or three tildes (~~~) on lines before and after code:
```
function greet(name) {
return `Hello, ${name}!`;
}
```
Specify Language for syntax highlighting:
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
```
Markdown renderers apply language-specific syntax highlighting, dramatically improving readability.
Supported Languages
Most renderers support 100+ languages:
Common Languages:
```python # Python
```javascript # JavaScript
```typescript # TypeScript
```java # Java
```csharp # C#
```cpp # C++
```go # Go
```rust # Rust
```ruby # Ruby
```php # PHP
```sql # SQL
```bash # Bash/Shell
```json # JSON
```yaml # YAML
```xml # XML
```html # HTML
```css # CSS
```markdown # Markdown
```diff # Diff files
```text # Plain text
### When to Use Code Blocks
**Complete Functions**: Show full implementations:
````markdown
```python
def calculate_average(numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
**Configuration Examples**: Display complete config files:
````markdown
```yaml
database:
host: localhost
port: 5432
username: admin
password: secret
```
API Requests and Responses:
```json
{
"userId": 123,
"name": "Alice Johnson",
"email": "alice@example.com"
}
```
Shell Commands and Output:
```bash
$ npm test
> app@1.0.0 test
> jest
PASS tests/calculator.test.js
✓ adds numbers correctly (2 ms)
✓ subtracts numbers correctly (1 ms)
```
Multi-Line Algorithms: Show step-by-step logic:
```python
# Binary search implementation
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
```
Code Block Best Practices
Always Specify Language: Syntax highlighting isn't just prettier—it's functional. Colored keywords, strings, and comments guide comprehension.
Include Comments: Explain non-obvious code within blocks:
```javascript
// Debounce function prevents excessive API calls
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId); // Cancel previous timer
timeoutId = setTimeout(() => func(...args), delay);
};
}
```
Show Complete, Runnable Examples: Readers appreciate code they can copy and execute. Include imports, declarations, and cleanup:
```python
import requests
def fetch_user(user_id):
response = requests.get(f'https://api.example.com/users/{user_id}')
return response.json()
# Example usage
user = fetch_user(123)
print(user['name'])
```
Use Line Length Limits: Keep lines under 80-100 characters when possible for better rendering on narrow screens.
Separate Setup from Core Logic:
```javascript
// Setup
const API_URL = 'https://api.example.com';
const API_KEY = process.env.API_KEY;
// Core function
async function fetchData(endpoint) {
const response = await fetch(`${API_URL}/${endpoint}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
return response.json();
}
```
Indented Code Blocks (Legacy Syntax)
Standard Markdown also supports indented code blocks—indent every line by 4 spaces or 1 tab:
Normal paragraph text.
function example() {
return "indented code block";
}
Back to normal text.
Limitations:
- No syntax highlighting
- No language specification
- Easy to accidentally create with improper indentation
- Harder to visually distinguish from normal paragraphs
Recommendation: Use fenced code blocks (triple backticks) instead. They're clearer, support syntax highlighting, and are the GFM standard.
Showing Literal Backticks
Because backticks are the delimiter, displaying a literal backtick takes a small trick: wrap the snippet in a longer run of backticks than it contains, and pad the inside with a space. The outer run becomes the delimiter; the inner backtick renders as text.
To show a single backtick inline, delimit with double backticks:
Use `` ` `` to open an inline code span.
That renders the lone backtick: use ` to open an inline code span. The rule generalizes—use N+1 backticks as the delimiter to display N backticks. So to show a double backtick, delimit with triple backticks, and so on.
The same idea scales up to whole blocks. To display a fenced code block (three backticks) as literal text—exactly what this article does to show its own examples—wrap the outer fence in four backticks:
````markdown
```javascript
console.log("This whole block is shown literally");
```
````
The four-backtick outer fence is one character longer than the inner three-backtick fence, so the renderer treats the inner fence as content instead of a delimiter. Triple tildes (~~~) work as an alternative fence for the same reason: when your sample already contains backticks, switching the outer fence to tildes sidesteps the collision without counting characters.
Advanced Code Block Features
Line Highlighting
Some renderers support highlighting specific lines:
```javascript {2,4-6}
function processData(data) {
const filtered = data.filter(item => item.active);
const mapped = filtered.map(item => ({
id: item.id,
name: item.name,
timestamp: Date.now()
}));
return mapped;
}
```
Highlights lines 2, 4, 5, and 6, drawing attention to key code.
Line Numbers
Many renderers add line numbers automatically or support enabling them:
```python showLineNumbers
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
```
Code Titles
Some systems support code block titles:
```javascript:fibonacci.js
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
```
Diff Highlighting
Show code changes with diff syntax:
```diff
function greet(name) {
- return "Hello " + name;
+ return `Hello, ${name}!`;
}
```
Lines starting with - appear red (removed), + appear green (added).
Common Mistakes and How to Avoid Them
Mistake 1: Using Code Blocks for Single Identifiers
Wrong:
userId
Right:
The `userId` parameter identifies the user.
Code blocks for single words waste space and break flow.
Mistake 2: Missing Language Specification
Wrong:
```
def hello():
print("Hello")
```
Right:
```python
def hello():
print("Hello")
```
Syntax highlighting dramatically improves readability.
Mistake 3: Mixing Code and Output Without Distinction
Confusing:
```
$ npm test
PASS tests/app.test.js
```
Clear:
```bash
$ npm test
```
Output:
```
PASS tests/app.test.js
✓ renders correctly (12 ms)
```
Separate commands from output for clarity.
Mistake 4: Incomplete Examples
Frustrating:
```javascript
await fetchData();
```
Helpful:
```javascript
const API_URL = 'https://api.example.com/data';
async function fetchData() {
const response = await fetch(API_URL);
return response.json();
}
// Usage
const data = await fetchData();
console.log(data);
```
Readers need context—imports, definitions, usage.
Choosing Between Inline and Block
Use Inline Code When:
- Referencing identifiers within sentences
- Mentioning single commands or functions
- Discussing parameters in prose
- The code is 1-5 words
Use Code Blocks When:
- Showing complete implementations
- Displaying configuration files
- Presenting API examples
- The code is multiple lines or complex
Gray Area Example: For a short command with options, either works:
Run `git commit -m "Initial commit"` to commit changes.
Or:
Commit your changes:
```bash
git commit -m "Initial commit"
Choose based on emphasis—inline maintains flow, blocks emphasize importance.
## Preview Your Code Formatting
Want to see how your inline code and code blocks render? Our Markdown Preview tool provides real-time rendering with full syntax highlighting support. Test different languages, check formatting, and ensure your code examples look exactly as intended—paste an example below and watch it render live.
Mastering Code Presentation
Effective technical documentation depends on clear code presentation. Inline code marks identifiers without disrupting reading flow. Code blocks showcase complete examples with syntax highlighting that guides comprehension. Master both, understand when each applies, and your documentation will communicate technical concepts with clarity and precision that benefits every reader.
The difference between inline code and code blocks isn't just syntactic—it's semantic. One preserves sentence flow while marking technical terms; the other creates visual separation that signals "stop and read carefully." Choose wisely, and your code examples become powerful teaching tools rather than confusing obstacles.