CSS Variables

Overview

By reading the title of the blog, we know many of you will say “what’s new” in this. It is already there with CSS preprocessors. But here we are talking about native CSS Variables which can also be referred to as “Custom Properties”.

Benefits

These days we usually have complex websites with multiple lines of code in CSS files with repetitive values. For example, we need to change a color that is used multiple times in the file then we need to globally search and replace that color which is obviously a tedious task. By using CSS Variables, such tasks will be done within a fraction of time. Even it is better to memorize the variable for example “primary-color” rather than the hex code for that “#3f7d6b”. It will work based on scope and inheritance. Don’t worry about it now, we will go through this in the latter part of the post.

As we might have a few mates who might have a view that we already have such features with CSS preprocessors then let us shed some light on this. The primary difference between CSS preprocessors variables and native CSS variables is that Sass variables are static and lexically scoped whereas CSS Variables are dynamic and scoped to the DOM.

Implementation

CSS Variables should be defined within the selector. For defining the variable that is accessible globally it should be defined within :root or body selector. Variable name precedes with double dashes(–).

Syntax

For Example

Result:

css_image1

Conclusion

I hope this blog will help you understand the CSS Variables and be helpful to you in your future projects.

mm

Priya Patel Web Designer

I am a Web Designer at Yudiz Solutions Pvt. Ltd - a leading Web and Mobile Apps development company. In my free time I learn new things about latest web design tools and techniques.

Leave a Reply

Top