Making the most of variables in CSS

Making the most of variables in CSS

An overview of CSS variables and how they help us write cleaner CSS code

ยท

5 min read

Photo by Pankaj Patel on Unsplash

As many developers would agree that variables are one of the most important features of programming languages, personally I do think the ability to use variables is what defines a programming language, which is why HTML IS JUST A MARK-UP LANGUAGE! ๐Ÿ˜‚. Violence

The aim of this article is to help you utilize more, the power of variables in CSS as well as pointing out perfect instances where they should be employed, with examples of course.

Let's jump right in.


Using variables in CSS

Like in every other programming language, variables are used to store values as well as expressions for later use, not necessarily later in time but rather later down the source code or outside of it, if exported. Any computation or value in a source code can only be reused if it is stored in a variable. CSS variables are defined with a double hyphen followed by the variable name (no spacing), for example:

--primary-color: blue;

This value assigned to this variable can then be used by calling the var() CSS function, like so:

background-color: var(--primary-color);

There is also an option to set a default in the case where the variable you are trying to access isn't defined or available, the default can be passed as a second argument to the var() function, for example:

background-color: var(--primary-color, gray);

Note that for a variable to be valid and available for use in an element, it must have been defined in an ancestor element, a variable from a child element cannot be accessed in its parent or any other higher-order elements, which is why it is best practice to define your variables in the body element like so:

body {
    --cards-color: purple;
    --buttons-width: 8rem;
}

This way, the variables are accessible throughout the body element which is like the Adam of all other elements that are visible on the DOM.

When and why should we use variables in CSS?

Our definition of variables takes us to the first and more obvious benefit of making use of variables in CSS, Reusability.

Storing a value in a CSS variable allows for the stored value to be used across the file, in more than a single place if needed. This allows many properties to share value from a single origin, making it easier to alter as many properties sharing the stored value from the point of definition, where the variable got defined.

It is a common convention to define variables before they are used as every programming language processes its source code from top to bottom with very rare exceptions.

Now let's talk about some sub-benefits of having multiple properties share value from a single definition point.

Source-code Readability

Using relevant and readable classes and IDs in the page's mark-up sure improves readability in our CSS as we are able to target elements based on what they represent, for example, a div with a class name of "user-profile-card" is self-explanatory to a reasonable extent, but imagine how much more clarity you can create for your future self and every other person who gets to read your source code by using variables with a good naming convention that corresponds with the value which they hold if done right, your source code will be very readable to anyone regardless of their programming experience and this is definitely what you want as a software engineer.

Uniformity

brian-mcgowan-LObpG0ku8VM-unsplash.jpg

Photo by Brian McGowan on Unsplash

With CSS variables, you can ensure that all similar entities in your app share the same style source and that any intended changes are applied to all these entities at once without having to style them individually. A Codepen example that demonstrates both readability and uniformity using variables:

Responsiveness

This one is more of a personal practice than a common convention, the idea is that rather than writing media queries for entities that need to be altered with respect to the viewport, why not store the dynamic values in variables and write one single media query to alter these variables with respect to viewport dimensions. The benefit of this approach is even more obvious when similar attributes of different entities have to respond to viewport changes.

Theming

This case is a more advanced one where you can store color or other theme-defining properties in variables and alter a whole set of them together in response to the right action to cause a whole theme change in your application. I made use of this approach in a project where I implemented dark/light mode toggle using pure HTML and CSS. Here is a Codepen for that:

Computation of values

This is another benefit that I consider to be more advanced, the concept here is that you can use numeric-valued variables in the CSS calc() function to derive some top-level optimizations like sizing without writing too many lines of code. This is something I'll want to discuss in another article to keep this one to a reasonable length. A quick snippet of this idea in play:

.big-buttons {
    width: calc(var(--button-width) * 2)
}

Conclusion

This piece started with a brief introduction to CSS variables, then we talked about how they are used and the cool benefits that come with using them, wrapping it up with some more advanced use cases.

ย