A few ways of specifying per-theme colours in only CSS
18 points by chrismorgan
18 points by chrismorgan
I was surprised to see my favorite method not listed here, which uses some less known rules of CSS custom properties: https://kosalab.dev/posts/no-duplication-css-theming
The approach does not require duplication, is flexible enough to support theming, is widely supported (afaik), and works with any CSS value, not just colors!
Ah, the space hack. I had quite forgotten about that nasty thing that broke so many tools that had made reasonable assumptions about the insignificance of whitespace…
I’ll consider adding something about it on Monday.
Isn't possible to simplify with:
:root {
color-scheme: light dark;
}
:root:has(#theme-dark:checked) {
color-scheme: dark;
}
:root:has(#theme-light:checked) {
color-scheme: light;
}
Then only rely on @media (prefers-color-scheme: XXX)?
Instead of color-mix I prefer using relative colors with the hsl or oklab calc syntax. This way you can easily get color variations with the same saturation/lightness/hue.
I personally don't like the light-dark function as it's a bit too limiting (from this point of view I prefer the new if syntax) and I prefer having theme colors defined together and not scattered around in the stylesheet. Also a "good" dark theme variant often needs special rules and changes here and there and not just color changes and the light dark function is far too specific for this use cases
I forgot about relative colours. Probably because I wrote that technique off long ago because it’s sorely limiting—colour just doesn’t work like that, perceptual colour space or no. The best results never follow exact RGB/LCH/LAB/whatever values. They’re far too limiting. Also yellow is a pain. And if you’re trying to use the same chroma/hue/saturation values with two wildly different lightness values, for light and dark… well, these colour spaces are not at all symmetrical. It just doesn’t work very well. Acceptable colour schemes can be generated numerically in a decent colour space, but good colour schemes are not so generated.
I’m not saying relative colours are worthless, but for this sort of problem, I don’t think they’re a good solution. They’re probably not that far above keyframes rules in my mind.
Perhaps I should still add a section for it.
What about images per theme? I use <picture> with the media="(prefers-color-scheme: dark)" attribute to do dark/light. I find it a shame, because it means I can't (or, don't know how), do a CSS only theme switcher for my site.
I embed some CSS into my SVGs, so that's also a problem -- they can read the system theme and change their own colors, but (at least for an SVG in an <img> tag), they can't read the state of some radiobutton.
SVGs I could fix by embedding them directly into my page, which sucks, but it's an option. For the other images, I don't knoww.