Open Search

Quick reminder for CSS variables

May 3, 2017 9:15 am
Categorised in:
Reading Time: 1

CSS variables or CSS Custom Properties are apparently here with enough support that we can start using them in production if we are clever with our fallbacks for IE.

CSS Variables are declared thusly:

--color: #ff000;

And can be scoped to an element, be it a H1, the body or root. Indeed it seems they HAVE to be scoped to an initial element. So if we want a variable to be used throughout a document, we should declare in the root

:root{
     --color: #ff000;
}

And then called where required:

h1{
     color: var(--color);
}

We can provide a fallback to the variable value in case it’s not set

h1{
     color: var(--color, #0000ff);
}

And to gracefully degrade for older browsers we simply add a property before which can be overridden for the browsers that support variables.

h1{
     color: blue;
     color: var(--color, #0000ff);
}

And that briefly sums up the basic use of CSS Variables. CSS variables are useful for when dealing with media queries:


:root{
      --color: purple;	
}
@media screen and (min-width: 768px) {
     :root{
          --color: red;
     }
}
@media screen and (min-width: 960px) {
     :root{
          --color: blue;
     }
}
@media screen and (min-width: 1170px) {
     :root{
          --color: green;
     }
}
.variable{
      color: yellow; 
      color: var(--color);
 }

Squeezing your browser window should show this effect in practice

This joint was penned by @elmarko