CSS Tricks: Individually-Styled Markdown Elements

Markdown is used all the time, for example in GitHub readme.md files, in Slack messages, and in WordPress themes. For example, below is two HTML lists created with this Markdown:

The above Markdown renders to the following HTML:

The Markdown ultimately renders to the following output:

  • Item 1
  • Item 2

and

  1. Item 1
  2. Item 2
    • Sub a
    • Sub b

Problem

Pretty neat, but what if you want to style a particular Markdown list with, say, a bold blue list? Markdown renders to empty HTML tags like <ul>, <li>, <p>, etc. without class names, so there is no way to add a unique class identifier to a Markdown element.

Your first thought might be to wrap the Markdown in something like a <div class="bold-list"> ... </div> block. Let’s try that.

The above unfortunately renders to:

* Item 1
* Item 2

 

How about with some extra spacing as in the below mixed Markdown?

The above also problematically renders to:

* Item 1
* Item 2

Solution

Markdown doesn’t like to necessarily be mixed with HTML, and it certainly doesn’t like to be nested in HTML tags. So how can we style an individual Markdown element? Let’s use a neat CSS trick to easily style an individual Markdown element: the immediate sibling selector (+).

Consider this CSS:

Can you see what will allow us to render a specific ordered list in bold with blue text?

Let’s try this now:

With this neat CSS trick we get this output:

  1. Item 1
  2. Item 2
    • Sub a
    • Sub b

but this is not styled:

  1. Another item 1
  2. Another item 2

Here is a Codepen example to experiment with.

How it Works

The CSS immediate sibling selector (+) allows us to select an element immediately after the empty <div class="bold-list"></div>. If there is a Markdown ordered list after that selector, then we have effectively selected it with CSS and without class names. Since the Markdown is at the root level (i.e. not nested in HTML elements), it renders into HTML as it normally does. From here you can get creative.

For example, I use this trick for hanging indents.

The above CSS with an immediately preceding <div class="hanging-indent"></div> results in this nice bulleted hanging indent list.

CSS trick - hanging indent in a Markdown list
CSS trick – hanging indent in a Markdown list

This is a simple way to make Markdown more flexible and allow non-developers to style sections.