2023-02-04
Support light and dark color themes in CSS
Do you want you website to look different depending on user's color preference. This website supports both light and dark modes. Try changing the setting and see this site updating live.
Basic example🔗
}
{
}
}
So what happens here? By default background color of the web page will be white but in case user uses dart mode black color will be applied.
If you prefer to separate CSS styles into several files you can conditionally import them (OK, both files will be imported but only one matching the condition will be applied).
/* Apply styles from "theme-dark.css" if user uses dart mode */
/* Apply styles from "theme-light.css" if user uses light mode */
CSS variables🔗
It's 2023 now and if you don't care about supporting IE you can use CSS variables. Let's see how our example might look like with variables.
}
{
}
}
}
I think this example is self-explanatory. Instead of overriding the styles we override a variable.
JavaScript🔗
What if you want to change the theme with JavaScript? It is suprisingly easy to do:
if window.matchMedia && '(prefers-color-scheme: dark)'.matches
'(prefers-color-scheme: dark)''change',;
Thanks to this StackOverflow answer.
Zola🔗
Zola supports syntax highlighting of code snippets.
In your config.toml
:
[]
# Enable syntax highlighting
= true
# Instead of adding inline styles export styles as CSS files.
= "css"
= [
{ = "solarized", = "syntax-theme-dark.css" },
{ = "solarized-light", = "syntax-theme-light.css" },
]
And then in your CSS file:
Now your code snippets support light and dark modes.