What You Need To Know About CSS Variables

What You Need To Know About CSS Variables

When web projects grow bigger, their CSS usually becomes astronomically large and often times messy. To help us deal with this, new CSS variables are soon to hit mainstream browsers, giving devs the ability to reuse and easily edit repeatedly occurring CSS properties.

We’ve shown you how awesome stylesheet variables can be in our Sass and Less lessons, but these are pre-processors and require compiling before use. Now that variables are available in vanilla CSS, you can use them right away in your browser!

Defining And Using CSS Variables

Variables follow the same scope and inheritance rules like any other CSS definition. The easiest way to use them, is to make them globally available, by adding the declarations to the :root pseudo-class, so that all other selectors can inherit it.

:root{
    --awesome-blue: #2196F3;
}

To access the value inside a variable we can use the var(...) syntax. Note that names are case sensitive, so --foo != --FOO.

.some-element{
    background-color: var(--awesome-blue);
}

Support

Right now, only Firefox supports CSS variables out the box. However, versions 49 and up of Google Chrome will also ship with the feature enabled. If you are still on the older version of Chrome 48, you can enable this and some other new technologies by going to chrome://flags/ and finding Enable experimental Web Platform features. You can get more details here – Can I Use CSS Variables.

Below are a couple of examples, showcasing typical usage of CSS variables. To make sure they work properly, try viewing them on one of the browsers we’ve mentioned above.

Example 1 – Theme Colors

Variables in CSS are most useful when we need to apply the same rules over and over again for multiple elements, e.g. the repeating colors in a theme. Instead of copy-and-pasting every time we want to reuse the same color, we can place it in a variable and access it from there.

Now, if our client doesn’t like the shade of blue we’ve chosen, we can alter the styles in just one place (the definition of our variable) to change the colors of the whole theme. Without variables we would have to manually search and replace for every single occurrence.

For this demo to work properly make sure you are using one of these browsers.

:root{
    --primary-color: #B1D7DC;
    --accent-color: #FF3F90;
}

html{
    background-color: var(--primary-color);
}

h3{
    border-bottom: 2px solid var(--primary-color);
}

button{
    color: var(--accent-color);
    border: 1px solid var(--accent-color);
}
<div class="container">
    <h3>Dialog Window</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vulputate vitae nibh sed sodales. Maecenas non vulputate lacus, sed convallis eros. Cras sollicitudin, felis sit amet pharetra mattis, metus lectus ullamcorper magna.</p>
    <button>Confirm</button>
</div>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html{
    padding: 30px;
    font: normal 13px/1.5 sans-serif;
    color: #546567;
    background-color: var(--primary-color);
}

.container{
    background: #fff;
    padding: 20px;
}

h3{
    padding-bottom: 10px;
    margin-bottom: 15px;
}

p{
    background-color: #fff;
    margin: 15px 0;
}

button{
    font-size: 13px;
    padding: 8px 12px;
    background-color: #fff;
    border-radius: 3px;
    box-shadow: none;
    text-transform: uppercase;
    font-weight: bold;
    cursor: pointer;
    opacity: 0.8;
    outline: 0;
}

button:hover{
    opacity: 1;
}

Example 2 – Human Readable Names For Properties

Another great use of variables is when we want to save a more complex property value, so that we don’t have to remember it. Good examples are CSS rules with multiple parameters, such as box-shadow, transform and font.

By placing the property in a variable we can access it with a semantic, human readable name.

For this demo to work properly make sure you are using one of these browsers.

:root{
    --tiny-shadow: 0 2px 1px 0 rgba(0, 0, 0, 0.2);
    --animate-right: translateX(20px);
}
li{
    box-shadow: var(--tiny-shadow);
}
li:hover{
    transform: var(--animate-right);
}
<ul>
    <li>Hover on me!</li>
    <li>Hover on me!</li>
    <li>Hover on me!</li>
</ul>
html{
    background-color: #F9F9F9;
}
ul{
    padding: 20px;
    list-style: none;
    width: 300px;
}
li{
    font: normal 18px sans-serif;
    padding: 20px;
    transition: 0.4s;
    margin: 10px;
    color: #444;
    background-color: #fff;
    cursor: pointer;
}

Example 3 – Dynamically Changing Variables

When a custom property is declared multiple times, the standard cascade rules help resolve the conflict and the lowermost definition in the stylesheet overwrites the ones above it.

The example below demonstrates how easy it is to dynamically manipulate properties on user action, while still keeping the code clear and concise.

For this demo to work properly make sure you are using one of these browsers.

.blue-container{
	--title-text: 18px;
	--main-text: 14px;
}
.blue-container:hover{
	--title-text: 24px;
	--main-text: 16px;
}
.green-container:hover{
	--title-text: 30px;
	--main-text: 18px;
}
.title{
	font-size: var(--title-text);
}
.content{
	font-size: var(--main-text);
}
<div class="blue-container">
	<div class="green-container">
		<div class="container">
			<p class="title">A Title</p>
			<p class="content">Hover on the different color areas to change the size of this text and the title.</p>
		</div>
	</div>
</div>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html{
    background: #eee;
    padding: 30px;
    font: 500 14px sans-serif;
    color: #333;
    line-height: 1.5;
}

.blue-container{
	background: #64B5F6;
	padding-left: 50px;
}

.green-container{
	background: #AED581;
	padding-left: 50px;
}

.container{
    background: #fff;
    padding: 20px;
}

p{
	transition: 0.4s;
}

.title{
	font-weight: bold;
}

A Few More Tips

As you can see CSS variables are pretty straightforward to use and it won’t take much time for developers to start applying them everywhere. Here are a few more things we left our of the article, but are still worth mentioning:

  • The var() function has a second parameter, which can be used to supply a fallback value if the custom property fails:
    width: var(--custom-width, 20%);
  • It is possible to nest custom properties:
    --base-color: #f93ce9;
    --background-gradient: linear-gradient(to top, var(--base-color), #444);
  • Variables can be combined with another recent addition to CSS – the calc() function. Sadly, this works only in Firefox for now.
    --container-width: 1000px;
    max-width: calc(var(--container-width) / 2);

This concludes our article! Have fun trying out this new CSS feature but remember that this is still considered an experimental technology. For now, avoid using it in serious projects and aim to always provide fallbacks.

Presenting Bootstrap Studio

a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.

Learn more
Web Browser Frame DevKit Box Mouse Cursor
by Danny Markov

Danny is Tutorialzine's Bootstrap and HTML5 expert. When he is not in the office, you can usually find him riding his bike and coding on his laptop in the park.

1Share this post
2Read one more article
3Get your free book
Book Cover
jQuery Trickshots

Tutorialzine's advanced jQuery techniques book.

Download

No Comments

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links