Inline code with single backticks

In short
  • Single backticks quote a phrase inside a sentence; three backticks on their own lines quote a whole block.
  • Everything between the fences survives exactly as typed, indentation and Markdown characters included.
  • A language name after the opening fence turns on highlighting, and an unknown name costs you nothing but colour.
  • An opening fence with no closing fence swallows the rest of the file - The most destructive error in Markdown.

Wrap anything in single backticks and it renders in a monospaced font, with all Markdown processing switched off inside it:

Run `npm install` first, then edit `config/*.json`.
The `**bold**` example stays literal in here.

That second line is the whole point. Inside backticks, **bold** shows as four visible asterisks. An underscore in my_var_name does not italicise the middle. A <div> displays as text instead of becoming HTML. Inline code is the escape hatch for any character that would otherwise mean something.

When your code contains a backtick

Use more backticks on the outside than appear on the inside. Two, three, however many it takes:

``Use the ` character to start a code span``

``` The ``double`` case needs three ```

If your content starts or ends with a backtick, add one space of padding just inside the delimiters. The renderer strips exactly one leading and one trailing space, so `` ` `` produces a lone backtick. It looks absurd the first time. It is also how every Markdown tutorial is written.

What inline code is not for

It is not a highlighter pen. Using backticks to make a product name stand out gives a screen reader the wrong signal, and makes your prose look like a config file. Reserve it for literal things a reader could type or paste: commands, filenames, function names, keys, HTML tags. For emphasis use bold or italics, and to point at documentation use a proper link.

Illustration of a sentence with one phrase sealed inside a protective monospaced capsule

Fenced code blocks

For anything longer than a phrase, open and close with three backticks on their own lines:

```
def greet(name):
    return f"Hello, {name}"
```

Everything between the fences is preserved exactly: indentation, blank lines, punctuation, and every character that would otherwise be Markdown. Fenced blocks came from GitHub Flavored Markdown and are now supported by essentially every renderer worth using.

Tilde fences

Three tildes do the same job:

~~~
console.log("same result");
~~~

Tildes matter in one situation: when the code you are showing contains a backtick fence of its own. A ~~~ wrapper around Markdown that itself contains ``` keeps the two from colliding. Otherwise backticks are the convention. You cannot mix them on one block, because a fence opened with backticks must close with backticks.

Fence length and blank lines

Two rules decide whether a block closes cleanly:

  • The closing fence must be at least as long as the opening one, so a block opened with four backticks closes with four or more.
  • Leave a blank line before the opening fence and after the closing fence.

Skip that blank line and some parsers glue the block into the surrounding paragraph. It is a five-second fix that costs people twenty minutes of confusion.

The four-space indented block, and why fences won

The original 2004 Markdown had no fences. A code block was any run of lines indented by four spaces or one tab:

Here is an example:

    $ git status
    On branch main

Back to normal prose.

It still works in every renderer, and you will meet it in old README files and in Stack Overflow answers written a decade ago. Use fences anyway, for four reasons:

  • No language identifier. An indented block cannot be syntax highlighted, because there is nowhere to say what language it is.
  • Indentation is data. Python, YAML and Makefiles care about leading whitespace. Adding four spaces to every line and mentally subtracting them again is an unforced error.
  • Copy-paste breaks it. Pasted code arrives unindented, so you re-indent every line by hand after every edit.
  • It collides with lists. Inside a list item, four spaces already means "continuation of this item", which makes the two rules fight.

Treat the four-space form as something to read, not something to write.

Tip: Converting an old file is mechanical. Select the block, strip four spaces from every line, wrap it in fences, then add a language name. Most editors do the de-indent with a single Shift+Tab.

Language identifiers and syntax highlighting

Write the language name immediately after the opening fence, with no space:

```python
def greet(name):
    return f"Hello, {name}"
```

That word is called the info string. The renderer hands it to a highlighter such as Prism, highlight.js or Chroma, which colours keywords, strings and comments. Identifiers are case-insensitive in practice. An unrecognised one is harmless, because you simply get an uncoloured block. Guessing costs nothing, so always label the block.

Identifiers worth knowing

IdentifierCommon aliasesTypical use
javascriptjs, nodeBrowser and Node.js code
typescriptts, tsxTyped JavaScript, React components
pythonpy, python3Scripts, data work, examples
bashsh, shell, zshShell commands and scripts
consoleshell-sessionA terminal session including the prompt and its output
jsonjsoncConfig files, API responses
yamlymlCI pipelines, Kubernetes, front matter
htmlxml, svgMarkup and templates
cssscss, lessStylesheets
sqlpostgresql, mysqlQueries and schema
gogolangGo source
rustrsRust source
java-Java source
c / cppc++, cc, hC and C++ source and headers
php-PHP source and templates
markdownmdMarkdown source shown as an example
diffpatchChanges, with coloured plus and minus lines
textplaintext, txt, noneDeliberately no highlighting

diff blocks

The diff identifier colours lines by their first character: green for +, red for -. It turns a code block into a before-and-after with no extra tooling:

```diff
 function total(items) {
-  return items.length
+  return items.reduce((sum, i) => sum + i.price, 0)
 }
```

Note the leading space on unchanged lines. That space is what tells the highlighter to leave them neutral, and forgetting it is why half-coloured diffs look wrong.

Turning highlighting off on purpose

Label a block text when colour would mislead: log output, ASCII diagrams, directory trees, error messages, sample data. A highlighter fed a stack trace will cheerfully colour random words as keywords, which makes the output harder to read rather than easier. Choosing text is a real decision, not a fallback.

Illustration of a grey block of code gaining colour as a language label is attached to it

Code blocks inside lists, and fences inside fences

Inside a list item

A fence inside a list must be indented to line up with the item's text, or the list breaks in half around it. For a bulleted list that is usually two or three spaces; for an ordered list, three or four:

1. Install the dependencies:

   ```bash
   npm install
   ```

2. Start the dev server:

   ```bash
   npm run dev
   ```

The rule is the same one that governs all continuation content in Markdown lists. Three points cover it:

  • Indent to the first character of the item's text, never to the marker.
  • Give the opening and closing fence the same indentation.
  • Leave a blank line before the fence to keep strict parsers happy.

Watch out: Get the indent wrong and the numbering restarts at 1 after the block. That renumbering is the classic symptom, and it means the list ended at the fence rather than continuing through it.

Showing a fence inside a fence

To display Markdown that itself contains a code block, make the outer fence longer than the inner one. Four backticks outside, three inside:

````markdown
Here is how to write a code block:

```js
alert("hi");
```
````

This is the mechanism behind every tutorial that teaches Markdown, this page included. If the inner content already uses four backticks, use five outside. The alternative is a ~~~ outer fence, which never collides with backticks at all.

Where highlighting actually happens

Fences are near-universal. Colour is not, because highlighting is a separate library that the platform either bundles or does not.

PlatformFenced blocksSyntax highlighting
The editor on this siteYesYes, for any fence with a language tag
GitHub, GitLabYesYes, hundreds of languages, server-side
VS Code previewYesYes, using the editor's own grammars
Hugo, Jekyll, Astro, DocusaurusYesYes, once you enable a highlighter in config
Obsidian, NotionYesYes, with a language picker
Discord, SlackYesDiscord yes, Slack no
Plain marked or markdown-it outputYesNo, until you plug in Prism or highlight.js yourself
Email clients, most CMS comment boxesVariesNo

The preview here follows the same rule as the rest of that table. It runs highlight.js on any fence that carries a language tag, and leaves an untagged fence plain rather than guessing the language.

The practical consequence: never let colour carry meaning. If the reader must notice one specific line, say so in the prose above the block, or mark it with a comment inside the code. A highlighted keyword that renders grey somewhere else has communicated nothing. The Discord guide and the Notion guide cover what each app does with a fence.

Line length and horizontal scroll

Code blocks do not wrap in most renderers. A 200-character line becomes a horizontal scrollbar, and on a phone the reader sees the first third and swipes for the rest. Keep example lines under roughly 80 characters. Four habits get you there:

  • Break long shell commands with a trailing backslash.
  • Split long function calls across several lines.
  • Shorten placeholder variable names to something short and obvious.
  • Trim example URLs down to the part that matters.

If a block genuinely cannot be shortened, say what matters in the prose, so nobody has to scroll to understand the point. This is where raw HTML tempts people into a wrapping <pre> tag. Pasting a screenshot is worse still, since an image of code cannot be copied, searched or read aloud.

Common mistakes and how to fix them

The unclosed fence

This is the big one, and it is spectacular when it happens:

Broken:
```js
const a = 1;

Everything after this point is now code.
Headings, lists, links: all swallowed.

An opening fence with no matching close consumes the entire rest of the document. The tell is unmistakable: the page turns into one enormous monospaced block from a certain point downward. Scroll up to where the formatting died and add the missing ```. A closing fence needs its own line with nothing else on it, so const a = 1;``` does not count.

Tip: A live preview catches an unclosed fence the second you type it. That is the strongest argument for drafting in the editor rather than straight into a pull request description.

Smart quotes

Broken:  const greeting = “hello”;
Fixed:   const greeting = "hello";

Curly quotes are not the same characters as straight ones, and no compiler accepts them. Your Markdown renderer will not convert them inside a code block. The text may have been converted before it arrived, though: by a word processor, a chat app, a CMS editor, or macOS system-wide substitution. The same applies to -- becoming a dash. If pasted code fails with a baffling syntax error, look at the quotes first.

Pasting from a word processor

Copying code out of Word, Google Docs or an email drags along invisible passengers:

  • Non-breaking spaces that look identical to ordinary ones.
  • Tabs converted into variable-width indents.
  • Zero-width characters with no visible form at all.
  • Smart punctuation, as above.

The result looks correct and does not run. Paste through a plain-text step first: a text editor, a terminal, or the left pane of this site's editor, where you can see the raw characters before you commit them.

The fence that is indented too far

Broken:
    ```js
    const a = 1;
    ```

Four spaces at the start of a line already means "indented code block", so the fence characters get displayed as literal text. Unless the block sits inside a list item, keep fences flush with the left margin.

Language name typos

Writing ```JavaScipt costs you the colour and nothing else, so nothing looks broken. If a block that should be coloured is not, check the info string against the table above before blaming the platform. For everything else, see the complete Markdown guide, the quick reference table, or the FAQ.

Support data verified

Frequently Asked Questions

How do I create a code block in Markdown?

Put three backticks on a line of their own, your code underneath, then three more backticks on their own line. Add a language name directly after the opening fence, such as ```python, to get syntax highlighting. For a single word or command inside a sentence, use single backticks instead.

Why did the rest of my document turn into code?

An opening fence somewhere above has no matching closing fence, so it swallowed everything after it. Scroll up to the point where formatting stopped working and add the missing ``` on its own line. A live preview catches this the moment it happens.

Which language identifiers can I use?

Whatever your renderer's highlighter recognises, which on GitHub is several hundred names plus aliases. The everyday set is js, ts, python, bash, json, yaml, html, css, sql and diff. An unknown identifier just renders without colour, so a wrong guess costs nothing.

How do I show backticks inside inline code?

Use more backticks on the outside than on the inside, and pad with a space if the content starts or ends with one. Two outer backticks wrap content containing a single backtick, three wrap content containing two, and so on.

Do code blocks work inside tables?

Only inline code does. A fenced block is a block-level element and cannot live inside a table cell, where a newline ends the row. Put single-backtick code in the cell and move any multi-line example to a fenced block below the table.

What opens a .markdown file?

Any text editor. A .markdown file is the same thing as a .md file, only with the long spelling of the extension, and both are plain text underneath. Notepad, TextEdit, VS Code, Obsidian and your phone's notes app all open one with nothing to convert and nothing to install. To read it formatted instead of raw, drop it into our Markdown viewer, or rename it to .md so more apps recognise it on sight.

Keep learning

Try the Editor

Try the Editor