Introduction to CSS Variables
Learn about CSS variables.
A CSS variable is simply a value that you want to reuse, again and again, in your layout.
CSS variables are formally known as custom properties.
Why CSS variables
CSS variables give us a way to keep our code nicely organized and easy to update. For example, let’s say that we want to update the font color on certain parts of our page from gray
to darkslategray
. Let’s also say that we’ve used the CSS declaration of color: gray
in a CSS stylesheet that’s 500 lines long, and our color: gray
the property appears in, say, 30 places.
We need to find and replace our single CSS declaration in many places. Even if we used our code editor’s find and replace function, this is still a lot of repetitive and redundant work. Imagine having to update five different CSS declarations in a CSS stylesheet that’s a couple of thousand lines of code long, and you might see the problem that CSS variables fix.
Using CSS variables
Here’s the HTML, CSS, and the corresponding output:
Get hands-on with 1400+ tech skills courses.