A Look Into: Using CSS Variables

By . Filed in Web Design

Variables finally come to CSS. Yes, the CSS that we use everyday for styling webpages. We have disccused several times on using variables with CSS Pre-processors in our previos posts. Today, we are going see how to use it in regular CSS.

Declaring Variables

The variable in CSS is specified with the var-* prefix, like so.

var-primary-color: #333;

In the above code example, we created a CSS variable named primary-color. However, unlike in CSS Pre-processor, where we can declare variables independently, the variable in CSS should be nested under a CSS selector.

Here is an example:

html {
	var-primary-color: #333;
}

Additionally, when it comes to naming the variable, it is advised to follow the language naming convention.

In the case of CSS, it uses dash to separate the words in the property name. In JavaScript, the uppercase is used for the start of each new word e.g. variableNamesLikeThis.

Passing Variables

Now, the question is how do we apply the variable in CSS rules? We can apply the variable with the new CSS var() method. Let’s say we want to apply the primary color in the body, we can write it in this way:

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

It is worth noting that Chrome is the only browser that is currently experimenting this feature, and the -webkit- prefix is required for us to see the result. So, at the moment, here is how we actually should write the CSS rules.

html {
	-webkit-var-primary-color: #333;
}
body {
	background-color: -webkit-var(primary-color);
}

Scope

If you a JavaScript coder, you should already be familiar with the Scope concept. Similarly, it also applies to CSS variable. The value will be applied only to the elements where it is nested. Given our previous example, we can apply to all the elements as we declared it under the utmost element, html.

Let’s say we nest it under a div, like so

div {
	-webkit-var-primary-color: #333;
}

Certainly, that variable can only be applied in <div>.

Further Resource

Conclusion

Without a doubt, Variable would be a great addition to CSS. However, at the moment, this only works in Chrome. So, until W3C has given Recommended status for this module, using CSS-Preprocessor is the only viable option of using variable in CSS.

You can go to the demo page. If your browser supports it, you should be able to see the effect.

Author:

Thoriq is a writer for hongkiat.com. He has been dabbling in Web Design for 7 years and appreciates the giving nature of the web design community at large. He loves trying new things in CSS3 and HTML5. Apart from writing on hongkiat.com he also maintains creatiface.com.

Advertisement