DEV Community


Posted on

Explain Css variables Like I'm Five

I am stuck with css variables right now. Please can you explain it to me?

Top comments (4)

nestedsoftware profile image
Nested Software • Edited

Have you used something like sass to create your css files? if so, css variables are the same idea, only now you can do it natively in css. You don't need to create a separate sass file, styles.scss, and compile it to a styles.css file.

Instead you can define values for variables directly in your css file, then use those variables further down. In a traditional css file, you might have a "red" color that you use for a bunch of things. In the css file, you'd have the value for that color, like '#ff0000' hard-coded everywhere. If you wanted to change this red color to pink, you'd have to do a search and replace throughout the css file, making sure to only change the relevant styles and leave any others that just also happened to be red alone.

With css variables, you can define a variable like --main-highlight-color: #ff0000. Now you can use var(--main-highlight-color) in your css file wherever it applies. If you want to change that color, you just change it in the definition, and you'll see the change in any style that uses it.

laurieontech profile image

Using CSS variables is also a great way to enforce consistency across a project. Want to use a single shade of green and a complimentary color as the only hues? Awesome! Set them once and make everything else reference it.

juloelker profile image

Fantastic explanation

vuild profile image

Name a thing:

Use it anywhere:

Change the speed of this animation by altering the "length" at the top of the CSS:

Look through the CSS. Anywhere it says "length" will be replaced by that variable.