Preprocessors like Sass and Less certainly help to keep your CSS codebase organized and maintainable. Features like variables, mixins, loops, etc., by adding dynamic capabilities to CSS coding, contribute to minimize repetition and speed up your development time.
Lately, a few dynamic features have started to make their appearance as part of the CSS language itself. CSS variables or custom properties are already here and have great browser support while CSS mixins are currently in the works.
In this article, you’ll find out how you can start integrating CSS variables into your CSS development workflow to make your stylesheets more maintainable and DRY (Don’t Repeat Yourself).
Let’s dive right in!
What are CSS Variables?
If you’ve used any programming language, you’re already familiar with the concept of a variable. Variables let you store and update values your program needs in order to work.
let number1 = 2;
let number2 = 3;
let total = number1 + number2;
console.log(total); // 5
number1 = 4;
total = number1 + number2;
console.log(total); // 7
number2 are two variables which store the number 2 and 3 respectively.
total is also a variable which stores the sum of the
number2 variables, in this case resulting in the value 5. You can dynamically change the value of these variables and use the updated value anywhere in your program. In the snippet above, I update the value of
number1 to 4 and when I perform the addition again using the same variables, the result stored inside
total is no longer 5 but 7.
The beauty of variables is that they let you store your value in one place and update it on the fly for a number of various purposes. No need for you to add new entities with different values all over your program: all value updates happen using the same storage place, i.e., your variable.
CSS is mostly a declarative language, lacking in dynamic capabilities. You’d say that having variables in CSS would almost be a contradiction in terms. If front-end development were just about semantics, it would be. Fortunately, the languages of the web are very much like living languages, which evolve and adapt according to the surrounding environment and the needs of their practitioners. CSS is no exception.
In short, variables have now become an exciting reality in the world of CSS, and as you’ll soon see for yourself, this awesome new technology is pretty straightforward to learn and use.
Are There Benefits to Using CSS Variables?
The benefits of using variables in CSS are not that much different from those of using variables in programming languages.
Here’s what the spec has to say about this:
[Using CSS variables] makes it easier to read large files, as seemingly-arbitrary values now have informative names, and makes editing such files much easier and less error-prone, as one only has to change the value once, in the custom property, and the change will propagate to all uses of that variable automatically.
By naming your variables in ways that make sense to you in relation to your project, it’ll be easier for you to manage and maintain your code. For example, editing the primary color in your project will be much easier when what you need to change is one value for the
--primary-color CSS custom property, rather than change that value inside multiple CSS properties in various places.
What’s the Difference Between CSS Variables and Preprocessor Variables?
Preprocessors let you set variables and use them in functions, loops, mathematical operations, etc. Does this mean CSS variables are irrelevant?
Not quite, mainly because CSS variables are something different from preprocessor variables.
The differences spring from the fact that CSS variables are live CSS properties running in the browser, while preprocessor variables get compiled into regular CSS code, therefore the browser knows nothing about them.
This is not to say that you need to choose between one or the other: nothing will stop you from taking advantage of the super powers of both CSS and preprocessor variables working together.
CSS Variables: The Syntax
Although in this article I use the term CSS variables for simplicity’s sake, the official spec refers to them as CSS custom properties for cascading variables. The CSS custom property part looks like this:
You prefix the custom property with two dashes and assign a value to it like you would with a regular CSS property. In the snippet above, I’ve assigned a color value to
--my-cool-background custom property.
The cascading variable part consists in applying your custom property using the
var() function, which looks like this:
The custom property is scoped inside a CSS selector and the
var() part is used as value of a real CSS property:
/* The rest of the CSS file */
The snippet above scopes the
--my-cool-background custom property to the
:root pseudo-class, which makes its value available globally (it matches everything inside the
<html> element). Then it uses the
var() function to apply that value to the
background-color property of the container with ID of foo, which as a consequence will now have a nice light blue background.
That’s not all. You can use the same nice light blue color value to style other color properties of multiple HTML elements, e.g.,
border-color, etc., simply by retrieving the custom property’s value using
var(--my-cool-background) and applying it to the appropriate CSS property (of course, I recommend giving some thought to your naming convention for CSS variables before things get confusing):
You can also set the value of a CSS variable with another CSS variable. For instance:
–my-gradient: linear-gradient(var(–top-color), var(–bottom-color));
The snippet above creates the
--my-gradient variable and sets it to the value of both the
--bottom-color variables to create a gradient. Now, you can modify your gradient at any time anywhere you have decided to use it by just changing the values of your variables. No need to chase all the gradient instances all over your stylesheets.
Here’s a live CodePen demo.
See the Pen Setting Value of CSS Variable with Another CSS Variable by SitePoint (@SitePoint) on CodePen.
Finally, you can include one or more fallback value/s with your CSS variable. For example:
In the snippet above, #333 is a fallback value. If fallbacks are not included, in case of invalid or unset custom properties, the inherited value will be applied instead.
CSS Variables Are Case Sensitive
Continue reading %A Practical Guide to CSS Variables (Custom Properties)%