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”.
Topics
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
css-selector{ --variable-name: value; }
For Example
:root { --color: blue; --warning-color: yellow; } #alert { --color: red; } #warning { --color: var(--warning-color); } * { color: var(--color); } <p>I inherited color from the root element!</p> <div id="alert"> While I got red set directly on me! <p>I’m red too, because of inheritance!</p> </div> <div id="warning">I got color dynamically changed using script.</div> <script type="text/javascript"> document.documentElement.style.setProperty('--warning-color', 'orange'); </script>
Result:
Conclusion
I hope this blog will help you understand the CSS Variables and be helpful to you in your future projects.