Variables in CSS

CSS variables do not work on all browsers, don't implement it into your code without having fallbacks for IE and other unsupported browsers.

From day to day I write most of my stylesheets in Sass with a compiler running in the background to generate the CSS, I even have SFTP setup in Sublime Text to listen to the changes and upload the files to a dev environment on my DO droplet. Recently I discovered CSS variables (yes, maybe I am a little late to the party) and had a play around with them to see what they could do, so heres a little bit of an explanation of how they work.

CSS variables, similar to Sass variables are key value pairs that can contain small bits of information such as colour #fff, measurements 25px and string information such as font families 'Helvetica' which can be reused in your stylesheet to keep it DRY.

A CSS variable looks like this:

--theme-red: #f00;

Notice that the variable name is prepended with a double dash, this is important as it declares it as a variable. An example of using this in your stylesheet look like this:

div.block {
  background: #fff;
  border-color: var(--theme-red);
}

When calling a variable, use var() method to get the value. You can use this variable throughout your stylesheet by assigning the variable at :root:

:root {
  --theme-red: #f00;
}

You can see a demo of CSS variables here.

This article is my 4th oldest. It is 239 words long, and it’s got 0 comments for now.