Changing the Syntax Highlighting Style in Hugo

When building a website using Hugo, you might want to customize the syntax highlighting to match your site’s overall aesthetic. Hugo uses Chroma, a powerful syntax highlighting engine, to provide code highlighting out of the box.

In this blog post, we’ll guide you through the process of changing the syntax highlighting style in Hugo using Chroma, with the help of the hugo gen chromastyles command.

1. Explore Chroma Styles

Chroma offers a wide range of built-in styles that you can use to customize the look of your code snippets. To see a list of all available styles, run the following command in your terminal:

1
hugo gen chromastyles --list

This will show you a list of available styles, such as ‘monokai’, ‘solarized-dark’, ‘dracula’, and many more.

View Themes (on xyproto.github.io)

2. Preview Your Preferred Style

To preview how your chosen style will look when applied to your code snippets, use the hugo gen command,

For example, if you want to preview the ‘dracula’ style, the command would be:

1
hugo gen chromastyles --style=dracula > syntax.css

This command generates a CSS file called ‘syntax.css’ in your project’s root directory. Open this file in your favorite text editor to preview the style’s CSS rules.

3. Apply the Style

To apply your chosen syntax highlighting style to your Hugo website, you will want to include it with your current style system. It will be either raw css or built with sass. Because we can’t see this, we’ll just show how to attach the css file itself.

Move the ‘syntax.css’ file to your project’s ‘static/css’ directory. If the ‘css’ directory does not exist, create it first:

1
mkdir -p static/css
1
mv syntax.css static/css/

In your project’s layout, add a reference to the ‘syntax.css’ file. Usually, this is done in the ‘head’ section of your layouts/partials/head.html file:

1
<link rel="stylesheet" href="/css/syntax.css">

Save your changes and rebuild your site with hugo.

Your chosen syntax highlighting style should now be applied to your code snippets.