When I first started using CSS variables, I wasn’t fully aware of the potential. When used in the right way, we can shorten the time and effort to do specific things in CSS.

If you don’t know about CSS variables, I recommend you to read this article to learn about them. Once you’re good with it, it will be easier for you to follow along. The goal of this article is to focus heavily on useful use-cases for CSS variables that are not only about design tokens like colors.

Are you ready? Let’s dive in!

What’s The Problem?

If you’re using CSS variables just like CSS pre-proccerssors (Sass, for example), then you aren’t taking the full benefit of them. Consider the following:

:root {
    --brand-primary: #7777e9;
    --brand-secondary: #c96fde;
}

.title {
    color: var(--brand-primary);
}

…is no difference than writing the following in Sass:

$brand-primary: #7777e9;
$brand-secondary: #c96fde;

.title {
    color: $brand-primary;
}

Using CSS variables only for color variables isn’t wrong at all, but it’s like getting an Apple M1 MacBook to browse the internet, even though your old 2012 is still working fine. What’s the point of getting a cutting-edge computer to do the same job while you have a chance to use its full potential? That’s exactly what I feel about using CSS variables, you know, just for storing colors.

The goal of this article is to walk you through use-cases where CSS variables shine. Let’s dive in!

Use Cases And Examples

Longhand Properties

In some scenarios, you might need to tweak the longhand version of a property. For example, a padding property can differ from a component variation to another. Instead of rewriting the longhand again, we can use a CSS variable for the thing that will change, and it will be overridden via the variation CSS class.

#article #css

Practical Use Cases For CSS Variables
1.05 GEEK