Examples of using CSS variables in practice

When I first tried using CSS Variables, I didn’t have a complete understanding of their capabilities. Their correct use can significantly reduce the time and labor costs for solving certain tasks in CSS.


If you haven’t worked with CSS Variables yet, I recommend reading this article to familiarize yourself with them. Once you master them, the job becomes much easier. The purpose of this article is to focus on various practical uses of CSS variables beyond their use to create design markers such as colors.

You are ready? Then go ahead!

What is the main problem?

If you use CSS variables in the same way you use CSS preprocessors (for example in Sass), then you are not fully realizing their full benefits. Consider the following example:

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

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

And there is no difference with the example below in Sass:

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

.title {
    color: $brand-primary;
}

Yes, using CSS variables as color variables is by no means a bug. But it’s like buying an Apple MacBook M1 to surf the internet, even though your old desktop PC built in 2012 does just that well. What is the point of buying an ultra-modern computer and doing the same on it, without using the full range of its capabilities? As you can imagine, this is roughly how I think about using CSS variables to store color information.

The purpose of this article is to introduce you to a variety of practical use cases that fully explore the power of CSS variables. Let’s get started!

Examples and practical use cases

Complete property notation forms

In some scenarios, you might need to customize the full version of the property record. For example, the padding property can be different for different components. Rather than rewrite the full form of this property again, we can use the CSS variable for the component we want to change, after which it will be overridden by class variations in CSS.

<!-- Base component -->
<header class="page-header">
    <h2>...</h2>
    <p>...</p>
</header>

<!-- Component variation -->
<header class="page-header page-header--compact">
    <h2>...</h2>
    <p>...</p>
</header>
.page-header {
    --padding-start: 2.5rem;
    --padding-block: 2rem;
    padding: var(--padding-block) 1rem var(--padding-block) var(--padding-start);
}

.page-header--compact {
    --padding-start: 1.5rem;
    --padding-block: 1rem;
}

Note that to change the padding, we only need to change the value of the CSS variable. Without it, we would have to manually enter the full form of the padding padding property in order to change only one value in it.

.page-header {
    padding: 2rem 1rem 2rem 1.5rem;
}

.page-header--compact {
    padding: 1rem 1rem 1rem 2.5rem;
}

All of the above applies to the margin property as well.

CSS background properties

When it comes to CSS properties for working with the background, here again, CSS variables help reduce the amount of code we create. What’s more, they make the CSS itself easier to read.

Storing URL values

When working with the user interface, you may need to add some kind of image for decorative purposes. In such a case, using and background-image elements is a good solution. If the interface is to be dynamic, then the values ​​for the image must be substituted using JavaScript.

Without CSS variables applied, the corresponding HTML would look like this:

<section 
    class="newsletter" 
    style="background-image: url('/assets/ui/decoraitve/newsletter-lg-aj1891101.svg')">
</section>

But instead of directly changing the background-image property, we can do the following.

<section 
    class="newsletter" 
    style="--thumb:url('/assets/ui/decoraitve/newsletter-lg-aj1891101.svg')">
</section>
.newsletter {
    background-image: var(--thumb);
    background-size: cover;
    background-position: 100% 50%;
}

Note that you need to include the url () element without the CSS variable.

Background image position

In the above example, the background image is placed on the right. For right-to-left (RTL) layouts, the background position should be flipped.

.newsletter {
    --pos: 100% 50%;
    background-image: var(--thumb);
    background-size: cover;
    background-position: 100% 50%;
}

html[dir="rtl] .newsletter {
    -background-position: 0% 50%;
}

To simplify this task, we can use CSS Variables.

.newsletter {
    /* other styles */
    background-position: var(--pos);
}

html[dir="rtl] .newsletter {
    --pos: 0% 50%;
}

Angled Gradient Part 1

An angular gradient can also be applied when creating layouts for multiple languages. It may be 45deg by default, and may need to be changed to -45deg for RTL layouts.

.element {
    --angle: 90deg;
    background: linear-gradient(var(--angle), #4088vb, #C05858);
}

html[dir="rtl] .element {
    --angle: -90deg;
}

Angular fade part 2

In the case of angular gradients, using CSS variables with radial gradients really makes positioning a lot easier. In the following example, the position of the gradient is changed using the –pos variable.

And here’s how you can do the same without CSS variables.

.card {
    background: radial-gradient(
        circle 200px at center top,
        rgba(64, 136, 203, 0.5),
        #f7f7f7
    );
}

Now let’s say we have some kind of .card-2 card and it needs to be in a different position. You need to write the following code:

.card-2 {
    background: radial-gradient(
        circle 200px at center top,
        rgba(64, 136, 203, 0.5),
        #f7f7f7
    );
}

This overwrites the entire gradient definition. Can you do better? Definitely. Note that the only configurable value for this option is the –pos variable.

.card {
    --pos: center top;
    background: radial-gradient(
        circle 200px at var(--pos),
        rgba(64, 136, 203, 0.5),
        #f7f7f7
    );
}

.card-2 {
    --pos: left top;
}

Clip-path property

A very useful use case for the CSS variable is when it changes clip-path: polygon () values ​​when switching from desktop to mobile.

In the above image, you need to reposition the vertices of the polygon. This is much easier with CSS variables.

.hero {
    --first: 4% 7%;
    --second: 80% 0;
    --thrid: 100% 95%;
    --fourth: 10% 100%;
    clip-path: polygon(var(--first), var(--second), var(--thrid), var(--fourth));
}

@media (min-width: 40rem) {
    .hero {
        --second: 96% 0;
        --thrid: 92% 82%;
    }
}

If you want to know more about the clip-path CSS property, here you will find an article by yours truly.

Checkbox element

A great example of using CSS variables is when used in conjunction with the hsla () color detection function. This way we can create dynamic components, which can then be changed by adjusting one or more CSS variables.

The first thing I did was define hsla () values ​​for the root element of the component.

.form-item {
    --primary-h: 240;
    --primary-s: 56%;
    --primary-l: 63%;
    --primary-alpha: 100%;
}

Now I can use these properties in the hsla () color detection function.

/* The circle that appears on hover */
.form-item__label:after {
    --primary-alpha: 0;
    background-color: hsla(
        var(--primary-h),
        var(--primary-s),
        var(--primary-l),
        var(--primary-alpha)
    );
}

.form-item__label:hover:after {
    --primary-alpha: 15%;
}

SVG code embedded in CSS

I was once working on a UI for a single client project and ran into this situation. We had a section with two ribbons (one on top and one on the bottom). I needed to change color, rotation angle and the size these feeds without having to create separate CSS for each one. The salvation was CSS variables!

First of all, I prepared the required SVG code in Adobe Illustrator. I have divided each tape into three layers:

  • bright areas;

  • dark areas;

  • base layer.

Then I exported this SVG code and placed it in elements so that I can easily reuse it. Note, I’ve also added the currentColor keyword! This is the very magical meaning that will make everything work.

Finally, we now need to define the size and rotation in CSS.

.tape {
    width: var(--size);
    transform: rotate(var(--angle));
}
<svg class="tape" style="--angle: 10deg; color: red; --size: 120px;" aria-hidden="true" focusable="false" viewBox="0 0 123 47">
  <use href="https://habr.com/ru/company/skillfactory/blog/554440/#tape"></use>
</svg>

Done. We’ve created our own SVG code that can be customized as needed. Impressive, isn’t it?

Create mixins (template mixins) like Sass

I learned about this interesting feature from the speech I recommend to watch Lea Verou. The idea is to set initial CSS variables for a specific property and then override them when needed.

Here’s an example of how we can use this feature. Very often I need the wrapper to be centered, for which I can add margin: 0 auto to the corresponding element of the wrapper. In cases where it is necessary to center some of our elements, we can do the following:

<div class="featured-section u-center"></div>
.u-center {
  --mx: initial;
  --my: initial;

  margin: var(--my) var(--mx);
}

.featured-section {
  --mx: auto;
  --my: 2rem;
}

First, I created a .u-center utility class with default values ​​for horizontal and vertical margins. I can add this class to an element and then override the CSS variables. This can be very useful, for example, if an element needs certain margins only on the top and bottom sides.

Using the calc () function

The calc () function in conjunction with CSS Variables can come in very handy. We can create some kind of base size for the component, and then, by changing only one variable, we can make it larger or smaller.

This can be useful in a wide variety of applications. Let’s assume that we need to create several variations for the user’s avatar.

.c-avatar {
  width: calc(var(--size, 32) * 1px);
  height: calc(var(--size, 32) * 1px);
}

Please note that I used the var (- size, 32) function. If the –size variable is not defined, the value 32 will be used as a fallback value. It’s important to specify 1px to add px to the resulting number.

This way, we can create variations of the classes by simply adding the CSS variable –size.

.c-avatar--medium {
    --size: 64;
}

.c-avatar--large {
    --size: 128;
}

Pseudo-elements

Using CSS variables, you can change the property of the pseudo-element as it inherits from the parent element. Consider the following example:

The section header contains a decorative purple line that is a pseudo-element. We can pass a CSS variable to a given header, and this pseudo-element will inherit it.

.section-title {
    --dot-color: #829be9;
}

.section-title:before {
    content: "";
    background-color: var(--dot-color);
}

But apart from that, we can also simulate the color change of the pseudo element using Javascript.

Inline Styles

Another example of useful uses for CSS variables is using them as inline styles. And here many possibilities open up for customizing any component by changing one or several variables.

Consider the following example.

.o-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(var(--item-width, 200px), 1fr);
    grid-gap: var(--gap);
}

We have a configured grid and a default grid item width of 200px. In the HTML code, we can override it by re-setting the value for the CSS variable.

<!-- Example 1 -->
<div class="o-grid" style="--item-width: 250px;">
     <div></div>
     <div></div>
     <div></div>
</div>

<!-- Example 2 -->
<div class="o-grid" style="--item-width: 350px;">
     <div></div>
     <div></div>
     <div></div>
</div>

Isn’t that useful? If you want to know more about CSS Variables with Inline Styles I have already wrote about this in more detail.

Conclusion

As you can see, there are many examples of using CSS variables besides defining colors with them. I am sure that what I have shown is only the most superficial options for their use. If you have come up with some unique use case of your own, share it in the comments!

If front-end development has long been a native element for you, you can already think about upgrading to Fullstack developer, a true all-rounder of web development who will be welcome on any large project. On our course, in addition to the modern program, you will find a lot of practice in different formats from teachers with experience in commercial development. Come to study, it will be difficult, but interesting!

find outhow to level up in other specialties or master them from scratch:

Other professions and courses

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *