Basic CSS Custom Property Use


After all these years I’ve still got a soft spot for CSS. I’ve been doing some poking around as I haven’t done a ton of CSS work recently and was feeling kind of out of the loop and a little itchy for some CSS fun. One of the more powerful additions of recent past (well, it’s actually been some years now at this point…I mean, what is time these days anyway???) is CSS custom properties (variables).

I think it’s sometimes easy to forget what we have available to us just straight out of the box as we are so often using tools that layer on top of vanilla CSS. I think CSS custom properties are a really great example of one of these. It’s a powerful feature of CSS and I think even in its most basic use it covers a large majority of the reasons why we reach for tools like Sass. I’m planning to dig in deeper and explore more complex use-cases (and I’ll share more as I experiment), but here’s your reminder that CSS custom properties are, in fact, a thing and that they are great and you should use them.

Quick, super basic example of how they work:

/*
Let's define some global properties we can use all over town. Probably
in a global.css stylesheet or something like that.
*/
:root {
  --color-primary: #0000ff;
  --spacer: 12px;
}

/*
Here we update that custom property form smaller screens. Maybe
we just want to snug things up a bit for smaller screens. We can use
that "spacer" property everywhere and get consistent spacing. They can
even be overwritten within a class and are scoped to that class only.
This is really the base idea behind building a design system with
vanilla CSS.
*/
@media (max-width: 800px) {
  --spacer: 8px;
}
/* widget.css */
.widget {
  background-color: var(--color-primary);
  padding: var(--spacer);
}