DEV Community

Chloe
Chloe

Posted on • Originally published at cgweb.co.uk on

CSS Variables

CSS Variables have been around for a while and designed to try and reduce duplication in CSS. They are a useful way to change multiple values at the same time. To create them you use a prefix with -- and can be used in declarations using var() function e.g.

:root { 
  --header-background-colour: red; 
  --secondary-background-colour: blue; 
  --text-colour: white; 
} 

header { 
  background-color: var(--header-background-colour); 
  color: var(--text-colour); 
} 

p { 
  background-color: var(--secondary-background-colour); 
  color: var(--text-colour); 
} 
Enter fullscreen mode Exit fullscreen mode

It is important to note that these are case sensitive so --bg-colour and --BG-colour are seen as two separate properties. To see the current support see caniuse.com there is good support in modern browsers although if you need to support everyone's favourite IE they won't work and instead, you will need to set a separate background property before using var e.g.

  background-color: red; // this will work in IE 
  background-color: var(--header-background-color); // this will not
Enter fullscreen mode Exit fullscreen mode

Inheritance

As with other CSS properties, variables will inherit so a good idea to set them in :root as shown above to make them globally available and therefore accessible to every element. You can then set in specific individual elements to overwrite these global values.

I have setup a simple example on codepen:

See the Pen CSS Variables by Chloe (@cgweb) on CodePen.

Top comments (0)