Theme-aware syntax highlighting for Hugo using SCSS + Chroma

Hugo static site generator has built in syntax highlighting for code blocks that uses Chroma udner the hood. The newer CLI, known as hugo-extended, finally supports SASS transpilation.

Using the power of SASS @import statements + prefers-color-scheme media queries or CSS class name toggles, we can apply separate themes for light vs dark modes. Tailwind CSS refers to these strategies as media vs class.

I am using solarized-dark256 for dark mode and solarized-light for light mode.

  1. Install hugo-extended: choco install hugo-extended or winget install Hugo.Hugo.Extended

  2. To generate the required classes, run these commands:

    hugo gen chromastyles --style=solarized-dark256 > .\assets\syntax-dark.scss
    hugo gen chromastyles --style=solarized-light > .\assets\syntax-light.scss
    
  3. Create a file assets\custom.scss and @import the generated CSS files:

    If you are using the prefers-color-scheme CSS media query to toggle light/dark modes:

    @import "syntax-light";
    @media screen and (prefers-color-scheme: dark) {
        @import "syntax-dark";
    }
    

    If your page is using a CSS class to indicate dark vs light mode, you can also wire these up using @import statements. This site has a theme toggle button on the bottom right that toggles the CSS class colorscheme-light or colorscheme-dark on the HTML body tag. To use these instead of the media queries, I do this:

    .colorscheme-light {
        @import "syntax-light";
    }
    .colorscheme-dark {
        @import "syntax-dark";
    }
    
  4. Make sure your hugo config.toml knows about the custom.scss file and that markup highlighting classes are enabled:

    [params]
    customSCSS = ["custom.scss"]
    
    [markup.highlight]
    noClasses = false
    
Did this post help you? Buy me a coffee!
Buy Me A Coffee
comments powered by Disqus