CSS Variables is a big win for Front-end Developers. It brings the power of variable to CSS, which results in less repetition, better readability and more flexibility.
In this example below, it's much better to create a variable for the #ff6f69
colour then repeating it.
/*THE OLD WAY */
#title {
color: #ff6f69;
}
.quote {
color: #ff6f69;
}
THE NEW WAY
:root {
--red: #ff6f69; /* <--- Declaring Variabke */
}
/*USING THE VARIABLE*/
#title {
color: var(--red);
}
.quote{
color: var(--red);
}
More flexibility in case you want to change colour.
Benefits
- Reduces repetition in your stylesheet
- They don't require any transpilling to work
- They live in the DOM, which opens up a ton of benefits
Declaring a Local Variable
You can also create local variables, which are accessible only to the element it's declared at and to its children. This makes no sense to do if you know that variable only will be used in a specific part of your app.
.alert {
--alert-color: #ff6f69; /*This variable can now be used by its children*/
}
.alert p {
color: var(--alert-color);
border: 1px solid var(--alert-color);
}
If you tried to use the alert-color
variable somewhere else in your application, it simply wouldn't work. The browser would just ignore that line of CSS.
Easier responsiveness with Variables
You can, for example, change the variables based upon the width of the screen:
:root {
--main-font-size: 16px;
}
media all and (max-width:600px) {
:root {
--main-font-size: 12px;
}
}
And with those simple four lines of code, you have updated the main font-size across your entire app when viewed on small screens.
How to access variables with JavaScript
Grabbing a CSS variable in JavaScript takes three lines of code.
var root = document.querySelector(':root');
var rootStyles = getComputedStyle(root);
var mainColor =
rootStyles.getPropertyValue('--main-color');
console.log(mainColor);
--> '#ff6f69'
To update CSS variables:
root.style.setProperty('--main-color','#88d8b0')
Currently, 77% of global website traffic supports CSS Variables.
βThanks For Reading | Happy Coding β
Get weekly newsletter of amazing articles I posted this week and some offers or announcement. Subscribe from Here
Top comments (2)
Hmmm, now I oftenly use root as it is a good practice and easy to maintain