Code Blocks in Markdown

Learn how to format and highlight code in your Markdown documents

What are Code Blocks?

Code blocks in Markdown allow you to display code snippets with proper formatting and syntax highlighting. They're essential for technical documentation, tutorials, and any content that includes programming examples. When writing technical content, code blocks are often used alongside tables, lists, and images to create comprehensive documentation. For technical or scientific content, you might also want to explore advanced Markdown features like Mathematics/LaTeX support.

Markdown provides two ways to format code. You can try both in our Markdown Editor:

  • Inline code for short snippets within a paragraph
  • Code blocks for multi-line code examples

Inline Code

For small pieces of code within a sentence, use backticks (`) to create inline code:

Markdown
Use the `print()` function in Python.

This will render as:

Use the print() function in Python.

Basic Code Blocks

For larger code snippets, you can create code blocks using triple backticks (```) at the beginning and end of the block:

Markdown
```
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet('World'));
```

This will render as:

function greet(name) {
  return `Hello, ${name}!`;
}

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

Syntax Highlighting

To enable syntax highlighting, specify the programming language right after the opening triple backticks:

Markdown
```javascript
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet('World'));
```

This will render with JavaScript syntax highlighting (colors may vary depending on the Markdown processor and theme).

Indented Code Blocks

In some Markdown flavors, you can also create code blocks by indenting each line with four spaces or a tab:

Markdown
    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n-1)

However, the triple backtick method is generally preferred as it allows for syntax highlighting and is more visually distinct in the raw Markdown.

Interactive Markdown Code Block Generator

Try It Yourself

Enter your code below and select a language to create a formatted code block in Markdown.

```javascript
function helloWorld() {
  console.log("Hello, world!");
}
```
function helloWorld() {
  console.log("Hello, world!");
}

Code Block Examples

JavaScript

Markdown
```javascript
// Define a class
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }
}

const person = new Person('John', 30);
console.log(person.greet());
```

Python

Markdown
```python
# A simple function to calculate fibonacci numbers
def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# Calculate the first 10 fibonacci numbers
for i in range(10):
    print(f'fibonacci({i}) = {fibonacci(i)}')
```

HTML & CSS

Markdown
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Page</title>
    <style>
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        .title {
            color: #0066cc;
            border-bottom: 2px solid #eee;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">Hello World</h1>
        <p>This is a sample HTML page with some CSS styling.</p>
    </div>
</body>
</html>
```

Best Practices for Code Blocks

1. Always Specify the Language

When possible, always specify the language after the opening triple backticks. This enables syntax highlighting and makes your code more readable. It also helps screen readers and other accessibility tools properly interpret the content.

2. Keep Code Blocks Focused

Include only the relevant code in your code blocks. Avoid excessively long snippets that include unnecessary code. If you need to show a larger context, consider breaking it into smaller, focused examples with explanations between them.

3. Add Comments

Include comments within your code to explain complex parts or highlight important concepts. This is especially helpful for readers who might not be familiar with the programming language you're using.

4. Escape Backticks When Needed

If your code contains backticks, you might need to escape them or use a different number of backticks to start and end your code block. For example, you can use four backticks to wrap code that contains three backticks.

5. Indent Consistently

Maintain consistent indentation in your code blocks. This improves readability and helps convey the structure of the code, especially in languages where indentation is significant (like Python).

6. Test Your Code

Whenever possible, test the code you're including in your Markdown to ensure it works as expected. Nothing undermines credibility faster than code examples that contain errors or don't run.

Try Code Blocks in Our Editor

Practice creating formatted code blocks in our interactive Markdown editor.

Got Feedback? 📢