DEV Community

An Introduction to CSS Variables

Sarah Chima on December 05, 2017

One feature that makes preprocessors like Sass and Less appealing is the ability to use variables with them. Recently, I wrote an article on SASS V...
Collapse
 
foresthoffman profile image
Forest Hoffman

Oh cool! I didn't know vanilla CSS variables were a thing. Thank you! :)

Collapse
 
sarah_chima profile image
Sarah Chima

:)

Collapse
 
smontiel profile image
Salvador Montiel

Great post! πŸ‘
So do you come from future?
Android 62, hu! πŸ˜πŸ˜‰

Collapse
 
sarah_chima profile image
Sarah Chima

πŸ˜‚πŸ˜‚πŸ˜‚. Thanks for pointing that out.

Collapse
 
smontiel profile image
Salvador Montiel • Edited

Thanks to you, Sarah!

Collapse
 
itsjzt profile image
Saurabh Sharma

the best thing is css variables can be updated at runtime by javaScript 😁

Collapse
 
sarah_chima profile image
Sarah Chima

Ikr😊😊

Collapse
 
facundocorradini profile image
Facundo Corradini

Now that's a great reading!

The variables syntax is extremely weird though... But I got the feeling it's actually a nod to BEM, as CSS variables (unlike pre-procesor variables) really excel at making modifiers. That's actually my favourite feature of CSS vars.

Check this pen out :) codepen.io/facundocorradini/pen/Rx...

There I demonstrate how redefining a variable on a simple class selector (modifier) can influence a dozen properties distributed throughout several selectors. It's literally a single line for what would otherwise take 10, so it's a full order of magnitude drier! :D Any input will be appreciated ;)

Now going back to the OP, there are some things I think needs clarifying:

  • "There's no scope" might be an overstatement. There is no code block scope as SASS would, but DOM inheritance scope instead. Which actually, is great. Generally CSS vars are declared at the :root element (/ the html tag) to make them global, but nothing stops you from declaring them anywhere in the DOM tree.

  • For media queries... remember you can't set up the break points a variables. It might sound silly for some, but I know many has those as SASS variables for whatever reason. CSS vars won't let you do that (I tried, I failed :p), so one more reason to keep our good ol' pre-processors as well.

Collapse
 
belhassen07 profile image
Belhassen Chelbi

great post Sarah

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you :)

Collapse
 
sanjay555 profile image
Sanjayshr

Good to know but what about production ? say you have 50% customers out of 100 who uses IE ?