HomeWeb WorldCSS3Using CSS variables

Using CSS variables

CSS Variables are entities that hold values which can be reused throughout your stylesheet document.

They are formerly known as custom property and can be defined using the following notation

--property-name: value;

Once you have defined the property to access the value of the same, you have to use the var() function, example for the same would be:

.element-class {
    color: var(--property-name);

Nowadays, most of the websites have large amounts of CSS usage, often with a lot of repeated values. For example, the font size or color might be used in so many different places, and any change in the color or the font size means a global search on the CSS file and then replacing it the new value.

Here CSS variables come into the picture to save this massive find/replace action, they allow us to change the value at just one location, which will be then used automatically where ever that variable has been accessed.

An additional benefit is semantic identifiers. For example –main-text-color is easier to understand than #00ff00, especially if this same color is also used in another context.

CSS Variables are subject to the cascade, and inherit their value from their parent.

Want some more details on CSS variables, check it out in the W3C Spec, or on the Mozilla Developer Network.


Most Popular