One of the reasons why years ago I started to use SCSS in favour of basic CSS was the ability to use variables, as I do in other programming languages.
But since then CSS added a pletora of new features, and one of those are CSS variables.
Here I'm going to explain in simple terms how you can use them and how they work.
How to create a variable
A variable works exactly as any other CSS properties, you still define them as a property of an element or pseudoelement, and the only difference is that the name must start with a --
, something like this:
:root {
--main-bg-color: green;
}
The variable scope and the :root
pseudoelement
As you noticed I used a pseudoelement :root
, this is used to cast the variable to the entire document, but if you want you could define a variable only to a specific element, for example:
p {
--paragraph-color: red;
}
So with the above, if you try to use the variable above, it will work only on that specific element, but not on others, like a div
or h1
.
But the idea of having variables is reusability, and limiting the scope of action of a variable to a single element kinda defeats the purpose of variables all together in my opinion, but there could be cases where it could be useful.
How to read a variable
To read a variable is rather simple, you just need to use the var()
function, and the syntax is var(<name-of-variable>, [fallback-value])
.
As you see it takes the variable name as first argument, and you can also pass a secondary value which is the default value, in case the variable is undefined.
Here a few examples:
:root {
--bg-color: white;
--font-color: blue;
--heading-color: #AAA;
}
body {
background-color: var(--bg-color);
color: var(--font-color);
}
h1 {
color: var(--heading-color);
}
p {
color: var(--paragraph-color, red); /* Red if --paragraph-color is not defined */
}
You could also chain the default value in case you need to check against multiple variables, for example:
p {
color: var(--does-not-exists, var(--neither-this-one, blue));
}
Here a link to a JSFiddle if you want to play around it.
But can I use it?
Of course you can! The only browser that doesn't support them is IE, which is now defunct, and unless you live in the past and this is 2012, you can start to to use it right now!
And that's pretty much it!
If you want to read in more details you can read the MDN docs about it.
Top comments (0)