2021-04-28
|~3 min read
|483 words
I keep hearing about CSS variables (or more properly, custom properties), but at work I’ve always used SCSS/SASS. Moreover, the variables have always been set up already when I arrived, so I’ve never really had to explore how to set up variables, or why we may have chosen to use SASS versus CSS variables.1
Working through Josh W. Comeau’s CSS-for-JS course, when I got to the first workshop, he provided a series of tokens. These felt like an ideal opportunity to figure out how I might take advantage of built-in CSS variables. It turns out to be much easier to get started than I would have suspected!
Let’s take a quick look at a minimal implementation. There are two steps:
var()
functionTo get started, we can place custom properties in the :root
psuedo-class. This is more of a convenience than anything. Like using the global object in Javascript, this is powerful in that all tags, classes, ids, etc. will have access to the :root
, but at the same time, it may not be where you want to store everything.
For now, we’ll use it though:
:root {
--gold-lighter: hsl(45deg, 100%, 50%);
--gold-darker: hsl(45deg, 100%, 40%);
}
Here, I’ve defined two different gold colors.
A quick word on scope with respect to custom properties. I alluded earlier to the :root
pseudo-class as analogous to the global object for Javascript. That also means that there’s an opportunities for name conflicts, shadowing, etc. since CSS uses specificity to determine which attributes to apply.
Take for example the following:
:root {
--black: black;
}
.my-class {
--black: white;
background-color: var(--black);
}
.other-class {
background-color: var(--black);
}
In this example, --black
is going to be black
, as it’s assigned in the :root
pseudo-class, except in my-class
where we assigned anew to be white
. This is certainly a contrived example, but it’s worth noting that variables can be defined at any level. The use of :root
is a convenience.
var()
Now that we have variables defined, using them is a matter of access. To do that, we can use the var()
function.
Let’s say we have a div in our markup that we want to use our new variables:
<div class="gold-gradient">Pretty colors!</div>
In our CSS, we could then add a background gradient like so:
.gold-gradient {
linear-gradient(45deg, var(--gold-lighter) 0%, var(--gold-darker) 90%)
}
There’s a ton more to learn about CSS Custom Properties, I’m sure, but just knowing how to use them (and knowing that it’s so easy!) makes me much more excited about exploring them more in the future.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!