A few ways of specifying per-theme colours in only CSS

18 points by chrismorgan


kosayoda

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!

vbernat

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)?

aziis98

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

deivid

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.