In Markdown, how to create sections which can expand and collapse again, like an accordion.

General format

Here we use the details and summary HTML5 tags as HTML in Markdown, which works GitHub. No additional JavaScript or CSS needed.

Markdown code:

<details>
<summary>TITLE</summary>

BODY CONTENT

</details>


When you click to expand the accordion, the attribute will be added to the outer element as: <details open="">

Result:

TITLE BODY CONTENT



Markdown and HTML

Warning: This approach works well in GitHub when it renders Markdown as HTML, but when Jekyll will renders the code it keeps the Markdown as plain text and does not render it as formatted Markdown.

HTML code is valid in Markdown documents, since everything gets converted to HTML when viewed.

Here we use HTML in the title of the accordion and Markdown in the body.

Markdown code:

<details>
<summary><b>Preview title</b></summary>

_Markdown is valid, but add empty lines to separate from the HTML tags._

- Bullet
- Points

</details>


Result when rendered with GitHub:

Preview title

Markdown is valid, but add empty lines to separate from the HTML tags.

  • Bullet
  • Points


Result when rendered with Jekyll:

Preview title _Markdown is valid, but add empty lines to separate from the HTML tags._ - Bullet - Points



Jekyll site

Example of writing Liquid code inside an accordion, when using the Jekyll static site generator.

Here we put a codeblock inside the expandable section, to show how to combine HTML and Liquid. Since is needed in particular for putting codeblocks inside HTML, since using trick backticks or indentation just gets shown literally and not converted to Markdown.

Sample Jekyll/Liquid code

Here is the code:

<details>
<summary>Preview</summary>

{% highlight ruby %}
puts 'Expanded message'
{% endhighlight %}

</details>


Sample rendered HTML

Using the code above in a Jekyll site, here is the result after building to plain HTML:

Preview

puts 'Expanded message'


If you want to see the HTML code that was generated, here it is. For readability, the output was wrapped.

<details>
<summary>Preview</summary>

<figure class="highlight">
    <pre>
        <code class="language-ruby" data-lang="ruby">
        <span class="nb">puts</span> <span class="s1">'Expanded message'</span>
        </code>
    </pre>
</figure>