Today I Learned - Rocky Kev

TIL Separating purpose and appearance in CSS

POSTED ON:

TAGS:

Separate your CSS variables by purpose and appearance.

What is this solving?

Look how hacky this to create a dark mode:

:root {
--white-bg: white;
}

@media (prefers-color-scheme: dark) {
:root {
--white-bg: black;
}
}

--white-bg is black? (that jackie chan meme)

Let's fix that.

:root {
--background: white;
}

@media (prefers-color-scheme: dark) {
:root {
--background: black;
}
}

This is a very simple example. Let's get more complex.

A better way to do that is to describe purpose.

Appearance is how the variable looks.
Purpose is the intent of the variable.

CSS variables named after purpose instead of appearance tolerate visual change. The variable name --accent is decoupled from the colour, which means changing the accent colour has no impact on its identity or consumers. In comparison the variables named after the colour are renamed each time the colour changes.

Via the refence at the bottom.

:root {
/* defined appearances */
--light: FloralWhite;
--dark: Navy;
--blue: RoyalBlue;
--red: Crimson;

/* defined purpose */
--textColor: black;
--foreground: --red;
--middleground: --blue;
--background: --light;
}

@media (prefers-color-scheme: dark) {
:root {
/* changing purpose */
--textColor: white;
--foreground: --blue;
--middleground: --red;
--background: --dark;
}
}

So the background is currently --light. But on dark mode, it's --dark.

Also in our example above, --light is FloralWhite. That makes it flexible, and more importantly, scalable. Maybe down the line, someone wants it Beige. Boom - a single line change.

MDN prefers-color-scheme

And https://www.callumhart.com/blog/css-variables-that-mimic-chameleons/


Related TILs

Tagged:

TIL the alternate keyword

If 'alternate' appears along with the stylesheet keyword, the linked file is an alternative stylesheet. It won’t be applied to the document, but it will be ready for when we need it.

TIL Logical Properties

For that sweet sweet Internationalization you want to avoid directional words like 'left', 'right', 'top', and 'bottom'.

TIL Using pseudo-classes in your querySelector!

let notTuna = document.querySelectorAll('.sandwich:not(.tuna)')