I used to show style my code snippets with some very simple CSS. It looked something like this:

This was done with minimal styling (background color, font) on the html tag <code>. This does not provide any granular control or ability to do language-based styling though. Luckily, there is an easy way to achieve much better styling for code blocks in Jekyll, with support for around 200 different languages. Since version 3, Jekyll uses Rouge for syntax highlighting out of the box. All you need to do to get advanced html tagging for your code blocks is:

{% highlight <language> %}

YOUR CODE

{% endhighlight %}

For example

{% highlight javascript %}

YOUR JAVASCRIPT CODE

{% endhighlight %}

(P.S. If you ever need to write out liquid tags like above, enclose the part with raw and endraw liquid tags)

If you do this and inspect your code, you will see that it has been tagged and is ready for advanced styling:

Now we only need to apply a CSS theme that will style these tags. You can see a list of available themes here. You can also create your own styles if you wish to do so. Next, use the Rouge-command “rougify” to create a CSS-file with the theme you choose:

> rougify style base16.dark > base16_dark.css

This will create the file in your project root. I prefer to place it in the assets folder. Now you just need to include it in your html. In my default layout html file I add this:

// default.html

<head><link rel="stylesheet" href=/assets/base16_dark.css /></head>

The code snippet we looked at in the beginning of this post now looks like this:

//import
import firebase from "firebase/app";
import "firebase/auth";

const firebaseConfig = {
//your config here
};

firebase.initializeApp(firebaseConfig);

//create auth instance
const projectAuth = firebase.auth();

Note that I’ve styled the code elements and the .highlight class (Rouge class) further in my main CSS file to make sure it scrolls if the code block is wide and also add some rounding to the corners of code blocks because I like the look of it:

code {
padding: 1.5rem;
display: block;
overflow: auto;
}

.highlight {
border-radius: 25px;
margin: 0px;
}

More From The Building this blog Series

JAMstack forms with Netlify

Series: Building this blog

Hosting a Jekyll site on Netlify

Series: Building this blog

Getting started with Jekyll

Series: Building this blog