Variables In CSS Without Sass/SCSS

August 14, 2018 by Andreas Wik

CSS variables are great. If you’ve done any programming at all, just a tiny bit of JS, you’ll feel right at home. You might think about SASS/SCSS when you hear “CSS variables”, but CSS does have variables available and the browser support is actually quite good.


Variables, what’s that?

In case you haven’t done any programming and have no idea what variables are – here’s a quick explanation…

Think of a variable as a container. You give this container a name and inside of it you store a value. The value could be a string, a number, pretty much anything. In the case of CSS variables we can store things like color codes, pixel/em sizes, opacity and more.

So what is this good for?

Imagine you have the color #c0c0c0 typed out at seven different places in your CSS document and need to change this color to something else, maybe a slightly darker color. Instead of having to change the hex code at all of these seven places, you could just change the value at one single place in the top of the document, where you declare your variable.

Continue reading to see how.


Variables in CSS

So to declare variables in CSS, just add them with the :root selector in the top, which means they’ll be available everywhere the document. Add two dashes before the name and give it a value, like so:

:root {
  --main-text-color: #515f7e;


Now, to use these, just replace the value with var(—variablename):

p {
  color: var(--main-text-color);



You can declare pixel values, percentages, colors and more.

Check out this CodePen using a few different types of values:

See the Pen mjQoPE by Andreas Wik (@andreaswik) on CodePen.


Mycket bra, mycket bra!

Share this article

Recommended articles