HTML inside Markdown

Markdown · Advanced · 10 min

A little HTML fills Markdown's gaps, but renderers strip or restrict it in ways you need to know.

CommonMark passes raw HTML through to the output. Inline tags (<kbd>Ctrl</kbd>, <sub>, <img width="200">) work inside paragraphs. Block-level HTML such as <div>, <details> or <table> starts an HTML block that continues until a blank line.

The blank-line rule matters: Markdown is not processed inside an HTML block, but it is processed again after a blank line. So to use Markdown inside a <details> element, leave blank lines around the content:

<details>
<summary>Show the logs</summary>

- this list **is** rendered as Markdown

</details>

Useful HTML in docs: <details>/<summary> for collapsible sections, <img width> for sizing, <kbd> for keys, <a id="..."> for stable anchors, <br> inside table cells, and <!-- comments --> that don't appear in the output.

Renderers sanitize HTML for security. GitHub strips <script>, <style>, <iframe>, event handlers and most attributes; some sites strip all HTML. Never rely on HTML for important content if the document might be shown elsewhere. And if your application renders user-supplied Markdown, always run the output through an HTML sanitizer; Markdown itself is not a security boundary.

Example

Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy. H<sub>2</sub>O.

<details>
<summary>Full configuration example</summary>

```yaml
server:
  port: 8080
```

</details>

<p align="center">
  <img src="docs/screenshot.png" alt="Dashboard screenshot" width="480">
</p>

<!-- TODO: add the benchmark table; this comment is not rendered -->

Remember

  • Raw HTML passes through; an HTML block ends at a blank line
  • Leave blank lines inside <details> to get Markdown rendered there
  • Renderers sanitize HTML; sanitize user-supplied Markdown output yourself

Watch out for

  • Writing Markdown directly after <details> without a blank line and seeing it shown as raw text.

Check yourself

  1. Why does a **bold** line right after <div> (no blank line) appear with literal asterisks?

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/#html-blocks