CSS Custom Properties

The 11ty logo

Digging into CSS Custom Properties.

Custom properties or CSS variables have been around for a few years now. I've used them, almost exclusively just to use them, but lets find out how to get more out of this exciting tool.

Why can't I just use my SASS or SCSS variables? They work right?

Sure they do, if you are using the same preprocessor everywhere. It is likely these days, that we will work on projects that use a lighter build stack, maybe just css. Custom Properties are just css, so they don't need to be reinterpreted. This also means that they are available to be altered by JS. Woot. That's a boon.

So far our advantages are, preprocessor agnostic, and accessible to js. Still feel like you can live with out them?

Ok, what about doing less work?

Lets look at this:

:root {
   --color-text: blue;
   --color-bg: white;
section {
   color: var(--color-text);
   background: var(--color-bg);
.dark {
   --color-text: white;
   --color-bg: black;

vs. a similar solution with some traditional scss vars:

$site-bg: white;
$site-text: blue;
$dark-site-bg: black;
$dark-site-text: white;
section {
   color: $site-text;
   background: $site-bg;
.dark {
   color: $dark-site-text;
   background: $dark-site-bg;

So the difference here is that we aren't having to redeclare properties, or define a bunch of
variables to account for variations. We just need to redefine the variables, and they'll remain scoped to just the 'dark' class. This is a significant advantage over our scss variable as our change is now 'dom aware'. Hooray.

Lets look at an example of how this would work with breakpoints. I found this example by Bjorn Ganslandt. Here we can see how much simpler this approach is than how we might handle it with scss variables. We don't need to add mixins that are slightly more complex to trace, or we don't need to redefine the same breakpoint variants in each component.