Markdown Code Blocks
You paste a snippet into a Markdown file and the preview mangles it. Underscores turn into italics, indentation disappears, or everything after the snippet turns into code. All of that comes down to a few rules about how Markdown marks code, and they're short.
Quick answer: put three backticks on a line by themselves above your code and three below it. Add a language name after the opening backticks, such as
python, if you want syntax highlighting.
To try the examples with live preview, use the Markdown Editor. New to the basics? See the Markdown Syntax Guide.
Three Ways to Mark Code
| Kind | How you write it | Use it for |
|---|---|---|
| Inline code | Backticks around the text | A command, filename or variable inside a sentence |
| Fenced code block | A line of 3+ backticks or tildes above and below | Multi-line code, terminal sessions, config files |
| Indented code block | Four spaces at the start of each line | Old-style blocks, mostly worth avoiding |
Fenced blocks are the one to learn. The other two are covered below.
Inline Code
Run `npm install` before starting the project.
Renders as: Run npm install before starting the project.
If the code itself contains a backtick, use a longer run of backticks to wrap it, and pad with a space on each side:
Use `` `backticks` `` to wrap code.
The span opens with a backtick string and closes with one of exactly the same length. One leading and one trailing space are stripped when both are present, which is what lets the code start or end with a backtick. A line break inside a code span turns into a space.
Inline code inside a table has one catch: a pipe character ends the cell, even in code. Write it as \|.
Fenced Code Blocks
```bash
npm install
npm run dev
```
The rules, all from the spec:
- A fence is three or more backticks, or three or more tildes. You can't mix the two in one fence.
- The opening fence can be indented by up to three spaces.
- Text after the opening fence is the info string. With a backtick fence it can't contain a backtick.
- The block ends at a closing fence that uses the same character and is at least as long as the opening one. It can be indented up to three spaces, with nothing after it but spaces.
- If there's no closing fence, the block runs to the end of the document, or of the list item or quote it sits in.
- A fenced block can start right after a paragraph without a blank line. Leaving blank lines around it is still easier to read.
- The content is literal.
#,*,_and[]show up as typed.
A tilde fence works the same way:
~~~python
print("Hello, World!")
~~~
Language Names and Syntax Highlighting
The first word of the info string is the language. CommonMark itself only passes it along (HTML renderers usually put it in a class on the code tag). The colouring comes from whatever highlighter the tool uses, so the same block can look different in different places.
On GitHub, language names come from the Linguist project. Its languages.yml file lists the valid names and aliases. For GitHub Pages sites, GitHub advises lower-case names. A few you'll use often:
| You write | For |
|---|---|
js, ts |
JavaScript, TypeScript |
python |
Python |
bash, sh |
Shell commands |
powershell |
PowerShell |
json, jsonc |
JSON, and JSON with comments |
yaml |
YAML config |
sql |
SQL |
html, css |
Web markup and styles |
diff |
Changes with + and - lines |
dockerfile |
Dockerfiles |
text |
Plain output, no colouring |
An unknown name usually gives you an uncoloured block, not an error. No name at all gives the same result.
A diff block is worth knowing because it shows removed and added lines in red and green on most highlighters:
```diff
- const port = 3000;
+ const port = process.env.PORT;
```
GitHub also reads a few special names. mermaid draws a diagram, and GitHub's docs list GeoJSON, TopoJSON and ASCII STL as well. See Mermaid Diagrams.
Extra text after the language name#
Some tools read more of the info string than the language. That's the tool, not Markdown. CommonMark leaves the rest of the info string up to the renderer.
- Docusaurus reads a title, line highlights and line numbers:
```jsx title="App.js",```jsx {1,4-6},```jsx showLineNumbers. - Hugo reads options in braces:
```go {linenos=inline hl_lines=[3,"6-8"]}.
On a renderer that doesn't know these, expect them to be ignored or, worst case, to stop the language being recognised. Test before using them in a shared README.
Showing Code That Contains Backticks
If your example has a triple-backtick fence in it, the first inner fence would close the outer block too early. Make the outer fence longer. Four backticks around three work, because a closing fence has to be at least as long as the opening one:
````
```js
console.log("Hello");
```
````
GitHub's docs describe the same trick with quadruple backticks. Tildes are the other way out: wrap backtick content in a ~~~ fence.
Indented Code Blocks
A line indented four or more spaces is code, with no info string, so there's no highlighting:
function hello() {
console.log("Hello");
}
Two things catch people:
- An indented block can't interrupt a paragraph. Leave a blank line before it, or the lines are just part of the paragraph. A fenced block doesn't have this problem.
- Inside a list, indentation means the list item first. A code block in a list item needs the list's own indent plus four more spaces. GitHub's docs say to indent by eight spaces in that case.
Fences avoid both problems, which is why I'd pick them over indenting.
Code Blocks in Lists, Quotes and Tables
In a list, indent the fence so it lines up with the item's text:
1. Install dependencies.
```bash
npm install
```
2. Start the server.
In a blockquote, start every line of the block, fences included, with > .
In a table, you can't. A GFM table cell holds inline content only, so a fenced block isn't possible there. Use inline code (and \| for pipes), or HTML where your platform allows it. See Markdown Tables.
Code Block Not Working? Check These
| What you see | Likely cause | Fix |
|---|---|---|
| Everything after my code is also code | No closing fence. The block runs to the end of the document | Add the closing fence |
| The block ends too early | The closing fence is shorter than the opening one, or a line inside matches it | Use a longer outer fence |
| My opening line turned into inline code | Backticks in the info string after a backtick fence | Remove them, or switch to a tilde fence |
| The lines became part of the paragraph above | An indented block placed straight after a paragraph | Add a blank line, or use a fence |
| The code fell out of my list item | The fence isn't indented to the item's text | Indent it to line up with the text |
| No colours | No language name, a name the renderer doesn't know, or a tool with highlighting off | Add a valid name, or enable the language in the tool |
| A pipe broke my table row | ` | ` inside inline code in a table |
| Markdown shows up styled inside my block | It isn't actually inside a fence | Check where the fence opens and closes |
Who Does the Colouring
| Where | Highlighting |
|---|---|
| GitHub | Uses Linguist to pick the language and a third-party grammar |
| Docusaurus | Prism. Some languages such as Java, C# and PHP need adding under prism.additionalLanguages, and the name must be Prism's (csharp, not cs) |
| Hugo | Chroma, on by default for fenced blocks. Turn it off with codeFences = false |
| MkDocs (Material) | pymdownx.highlight, with pymdownx.superfences for fenced blocks |
Colours depend on the theme or style, so don't write text that refers to them.
How I Write Code Blocks
- One idea per block. Two unrelated commands get two blocks.
- Leave the
$prompt out of commands people will copy, and put output in a separatetextblock. - JSON doesn't allow comments. If you need them in an example, say so, and use
jsoncwhere it's supported. - Fences over indenting, backticks over tildes, and the same fence style throughout a document.
- Keep lines short enough to read without sideways scrolling.
Sources
- GitHub Flavored Markdown Spec (fenced and indented code, code spans, tables)
- GitHub Docs: Creating and highlighting code blocks
- Linguist languages.yml
- Docusaurus: Code blocks
- Hugo: Syntax highlighting
Frequently Asked Questions
- 1
Do I have to add a language name?
No. A block without one still renders as code, you just don't get colouring.
- 2
Backticks or tildes?
Same result. Tildes help when the code itself is full of backticks. Either is fine, just don't mix the two characters in one fence.
- 3
How many backticks can I use?
Three or more. The closing fence has to use the same character and be at least as long as the opening one.
- 4
Is HTML inside a code block rendered?
No. The content of a code block is literal text, so tags show up as typed.
- 5
Can I add line numbers, a title or highlighted lines?
Not in Markdown itself. Some tools add them through the info string or a setting. Docusaurus and Hugo both do, with different syntax.
- 6
Can a code block interrupt a paragraph?
A fenced one can. An indented one can't, so it needs a blank line before it.
- 7
Which languages are supported?
Whichever the renderer's highlighter knows. On GitHub, check Linguist's
languages.yml. In other tools, check the highlighter's own language list.
