DEV Community

Cover image for What are CSS Variables?
Rahul
Rahul

Posted on

What are CSS Variables?

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;
 }
Enter fullscreen mode Exit fullscreen mode

THE NEW WAY

 :root {
    --red: #ff6f69;    /* <--- Declaring Variabke */
 }
 /*USING THE VARIABLE*/

#title {
    color: var(--red);
 }
 .quote{
    color: var(--red); 
 }
Enter fullscreen mode Exit fullscreen mode

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);
 }
Enter fullscreen mode Exit fullscreen mode

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;
    }
 }
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

To update CSS variables:

 root.style.setProperty('--main-color','#88d8b0')
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
himanshutiwari15 profile image
Himanshu Tiwari ๐ŸŒผ

Hmmm, now I oftenly use root as it is a good practice and easy to maintain