Using Global CSS Variables for Sass style results
If you have ever worked on a large site it is not uncommon to have a stylesheet with several thousand lines of code, each of which controls the look of specific areas your site design. In a case like this you may find that there is a tremendous amount of overlap in repeated elements such as colors, font styles or borders. So if you need to change a color for instance and it appears in multiple locations within your stylesheet you have to do a find replace search and often may need look at each instance to make sure you in fact want to change that attribute for a specific class or ID. This is not only inefficient it is tedious.
There is a brilliant solution though. Most developers are not aware that you can have a list of master attributes that you simply call within your stylesheet allowing you to globally change that attribute at any given time with a couple clicks. It is like being Sassy without using Sass. To use Global CSS Variables you just need to define them within your stylesheet by nesting them within the :root pseudo class and then call them where you want to use them. In HTML, :root represents the <html> element and is identical to the selector html, except that its specificity is higher.
So here is how this is all done. First define some Global CSS Variables at the top of your stylesheet like this:
:root {
--font-family-1: "Open Sans", Helvetica, sans-serif;
--color-1: #272e33;
--color-2: #0067d8;
--border-1: 1px solid rgba(204,204,204,.3);
--box-shadow-1: 1px -1px rgba(204, 204, 204, 0.4);
}
Then simply call those variables in specific Classes or ID’s within your CSS file like this:
.page-title {
color: var(--color-1);
font: 1.5em bold var(--font-family-1);
padding: 15px 30px;
background: var(--color-2);
}
Global CSS Variables are widely supported and have been for a long time now. The numbers in the table below specify the first browser version that fully supports the property.
| Property | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| :root | 4.0 + | 9.0 + | 3.5 + | 3.2 + | 9.6 + |

Leave a Reply
Want to join the discussion?Feel free to contribute!