Code spans and code blocks

Markdown · Practical · 10 min

Code is the most common content in technical writing, and fences with language tags make it readable.

Code spans wrap inline code in backticks: ` git status . Inside, nothing is interpreted, so * and _ are literal. To include a backtick, use a longer run of backticks as the delimiter and pad with spaces: ` ab ` ``.

Fenced code blocks use three (or more) backticks or tildes on their own lines:

def greet(name): return f"hello {name}"

  • The word after the opening fence is the info string, normally a language name (python, bash, json, diff). Renderers use it for syntax highlighting; GitHub also turns mermaid blocks into diagrams.
  • The closing fence must use the same character and be at least as long. To show a fence inside a block, wrap it in a longer fence (four backticks), as above.
  • Content is literal: no escaping needed.

Indented code blocks: lines indented by four spaces also form a code block. They can't carry a language and are easy to create by accident (for example, an over-indented paragraph after a list), so prefer fences.

Use diff blocks to show changes (+ and - lines get coloured), console or shell for terminal sessions, and keep long lines short since code blocks scroll horizontally.

Example

Run `npm install` and then `` npm run `build` `` (a span containing backticks).

```bash
npm install
npm run build
```

```diff
- const port = 3000;
+ const port = Number(process.env.PORT ?? 3000);
```

~~~markdown
```js
console.log("a fence shown inside a block");
```
~~~

    indented by four spaces: also a code block, but no language

Remember

  • Backticks for inline code; ``` fences with a language for blocks
  • Use a longer fence to show a fence inside a block
  • Prefer fences over four-space indented blocks

Watch out for

  • Indenting a paragraph four spaces by accident and having it render as a code block.

Check yourself

  1. You need to show a fenced code block, including its ``` lines, inside your document. What works?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: spec.commonmark.org/0.31.2/#fenced-code-blocks