Using CSS Variables

CSS variables also known as custom properties recently received broader browser support to a point where they can be used without much thought (except in IE 11 👎) Let’s take a look at some usage. First we’ll want to declare a css variable in a pseudo :root class so that is available throughout the CSS document:

:root {
    --base-color: blue;
}

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

CSS custom properties also inherit from a parent:

<div class="one">
  <div class="two">
    <div class="three"></div>
    <div class="four"></div>
  </div>
</div>
:root {
    --padding: 10px;
}

.one {
    padding: var(--padding);
}
.two {
    --padding: 20px;
    padding: var(--padding);
}

.three {
    --padding: 30px;
    padding: var(--padding);
}

.four {
    padding: var(--padding);
}

In the above example the div one will have padding of 10px, two will have 20 px, three will have 30 px, and four will inherit from it’s parent who is two which has a padding of 20px specified. Check our codepen to see it in action.

Some additional things to note:
1) CSS custom properties are case sensitive:

:root {
 --color: blue;
 --COLOR: red;
}

will be two different variables!

2) You can provide a fallback value in case that variable is not defined:

width: var(--custom-width, 33%);

3) CSS custom properties can be made conditional based on media queries:

:root {
	--padding: 15px 
}

@media screen and (min-width: 750px) {
	--padding: 30px
}

Read more about it here. Check the Can I Use report to see details on browser support.

Instagram Post