For this website, I wanted automatic syntax highlighting, but with a couple of custom modifications. Specifically, I wanted

  • Color theme approximating Sublime Text’s Monokai theme
  • Inline code with a light background
  • Automatic line numbers

Color theme

This mainly involves changing _syntax-highlighting.scss. The colors come straight from Pygment’s Monokai theme. However, the background color needs to be changed to a dark color. I’m using #272822 which matches Sublime Text. The fallback color for non-highlighted text is still dark though, so you also need to specify color: #f8f8f2 in order for everything to be readable.

Inline code

If you only make the changes above, they won’t work properly, because in _base.scss there are additional color options for the background. These options apply to all of the text, including inside highlight blocks. If you set a dark background in _base.scss, then you will have dark code everywhere, including when you have inline code. However, this looks strange when the rest of the page is white. The solution is to remove all of the color commands from the code formatting block. So mine looks like:

/**
 * Code formatting
 */
pre,
code {
    font-size: 15px;
    border: 1px solid $grey-color-light;
    border-radius: 3px;
}

code {
    padding: 1px 5px;
}

pre {
    padding: 8px 12px;
    overflow-x: auto;

    > code {
        border: 0;
        padding-right: 0;
        padding-left: 0;
    }
}

This has the result that the block of code above gets its background color from the highlight style, rather than the code style, which enables inline code snippets to retain black text with a white background.

Scrollbars

In the block above, you can see that I have overflow-x: auto. By default, it is set to scroll. This results in a horizontal scrollbar always appearing, even if it isn’t required. Setting it to auto will hide the scrollbar unless it is required.

Line numbers

Line numbers can be implemented within Jekyll in one of two modes. First, you can simply specify linenos in the highlight command for Liquid. This will put line numbers at the start of each line of code. However, this means that users cannot copy the code without including the line numbers. Alternatively, you can specify linenos=table, which solves this problem. However, the width of the table doesn’t match the text width, and wrapping doesn’t work properly.

A neat solution is provided by Drew Silcock, who uses CSS counters described by Alex Peattie. It comes down to defining a custom counter that’s placed in a separate element on the side of the code block. All that is required is to add the appropriate CSS lines to the end of _base.scss, and add lineanchors to the highlight command e.g. {% highlight css lineanchors %}