Hugo + css = dark/light theme
Example on how one can implement different themes in CSS, this has nothing to do with Hugo itself. While having a light/dark (CSS) theme is not critical for a website some users do appreciate it and it is simple and fast to implement.
This article was written for Hugo
Switching themes can be accomplished by using built-in CSS features. You will have to use
CSS variables, the gist is: define the default colors (and other variables) in
:root and overwrite them for your theme(s), in our case dark the
[data-theme="dark"] section. Now it is just a matter of toggling the
data-theme attribute to
dark and the dark theme values will be used on your site. You can add as many “themes” as you like, e.g.
[data-theme="purple"], and let the user toggle them.
The script itself is straightforward, the only gotcha is
"(prefers-color-scheme: dark)" which will be set if the user has its browser configured to prefer dark mode by default. The code can handle multiple “theme toggle” buttons on a single page and will synchronize their states upon changes.
To load the script as quickly as possible add it to your HTML head. Preferably before any other stylesheets (or scripts), for example see the snippet below.
Here is an example of the what a theme SCSS may look like. The default values are defined in
:root and, if desired, overwritten for the dark theme in
[data-theme="dark"]. Some variables are filled in by Hugo but this is entirely optional. You can also overwrite CSS rules in
[data-theme="dark"]. Be careful how you define color variables, in hex or RGBA notation, for example
color: rgba(var(--primary-color), 0.5) will not work if
--primary-color is defined in hex but will work when it is defined in RGB.
SCSS theme example
This is how you use colors variable in CSS, note that you can assign any value to variables.
CSS variable usage example
for non static websites one can also tie the user theme preference to a user account and save it server side so the preference is retained across multiple machines. For static websites this is not possible however. ↩︎
- Permalink: //oostens.me/posts/hugo--css-dark/light-theme/
- License: The text and content is licensed under CC BY-NC-SA 4.0. All source code I wrote on this page is licensed under The Unlicense; do as you please, I'm not liable nor provide warranty.