Using CSS Variables

Nice to hear! Variables are finally available in CSS. You can declare variables in CSS with var-* prefix, such as

html{
    var-pri-color: #0090f0;
} 

With above code, we created a variable with name ‘pri-color‘ and it stores ‘#0090f0‘ as value. There is an important condition with CSS variables and that is, you must declare them under CSS-Selectors else they will not work. Since we want to use the variable globally, we nested it under html{} selector.

You can use this variable with var() method as shown in following code

body {  
    background-color: var(pri-color);  
} 

Hence the whole code will be

html{
    var-pri-color: #0090f0;
}
body{
    background-color: var(pri-color);
}

Demo
(You will see blue background in following demo, if your browser supports CSS variables). Click here to load demo on new page.

See the Pen CSS Variables by Ankur (@asmhatre) on CodePen.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.