Hugo Chroma Syntax Highlighting Dark/Light Mode
Aug 3, 2021
2 minute read

I love a good dark mode theme, but in bright light settings sometimes I want something lighter. For my blog I strive to support both dark and light mode themes depending on the user’s settings.

Hugo uses Chroma for syntax highlighting. Since it renders the highlighted syntax at build time, it’s not immediately able to provide a dynamic dark/light style based on the user’s system settings. However, it is possible do this using media queries and css inlining.

config.toml (or whatever)

First, we want hugo to use classes instead of inline styles, so we can style with a stylesheet.

[markup]
  [markup.highlight]
    noclasses = false

Generate light and dark stylesheets

Determine which chroma styles you want to use for each color moe. See the Chroma Playground to cycle through the themes.

Use the hugo command to do dump the css for each color mode.

hugo gen chromastyles --style=emacs > layouts/partials/css/syntax-light.css
hugo gen chromastyles --style=monokai > layouts/partials/css/syntax-dark.css

Media Queries to change the stylese

Add the following media queries to your template. This will inline each of the syntax themes and enable them depending on the user’s prefered color mode.

<style type="text/css" media="screen">
@media (prefers-color-scheme: dark) { 
  {{ partial "css/syntax-dark.css" . | safeCSS }}
}
@media (prefers-color-scheme: light) { 
  {{ partial "css/syntax-light.css" . | safeCSS }} 
}
</style>

Test it out

I run Gnome on linux, so I use the Night Theme Switcher extension to quickly toggle dark and light mode for my whole system. Super handy for quickly testing prefers-color-scheme media queries!



comments powered by Disqus