Learn about CSS Variables Cheat Sheet

Learn about CSS Variables Cheat Sheet

CSS variables are an extremely useful feature and they enable us to do things we were compensating with SASS

Introduction

CSS variables are an extremely useful feature and they enable us to do things we were compensating with SASS. They are defined by the CSS authors and contain a specific values that can be reused wherever needed within our project. They use a custom notation and are accessed by using the var function.

Declaration

A CSS variable can be declared on any element, and we declare one like so:

div {
    --primary-color: green;
}

They are accessed by using the var function:

div {
    color: var(--primary-color);
}

An Example Use Case

Let's define a use case where we define the following CSS rules to our HTML:

.card-wrapper {
    padding: 1rem;
    display: flex;
    flex-direction: column
}
.card {
    border: 1px solid #0068d8;
    margin-bottom: 0.5rem
}
.card-title {
    padding: 1rem;
    background-color: #007bff;
    color: #fff
}
.card-body {
    padding: 1rem;
    background-color: #76b8ff;
    color: #fff
}

and apply them to the following HTML:

<section class="card-wrapper">
    <article class="card">
        <header class="card-title">
            Card 1
        </header>
        <main class="card-body">
            Lorem ipsum dolor sit amet...
        </main>
    </article>
    <article class="card">
        <header class="card-title">
            Card 2
        </header>
        <main class="card-body">
            Lorem ipsum dolor sit amet...
        </main>
    </article>
    <article class="card">
        <header class="card-title">
            Card 3
        </header>
        <main class="card-body">
            Lorem ipsum dolor sit amet...
        </main>
    </article>
</section>

Can you spot the repetitions? After analysing our CSS we come to a conclusion that the following properties are duplicates:

  1. padding
  2. color

Therefore, we can make an advantage of the new CSS feature. We can use CSS variables to define the padding and color for our elements. By declaring them on a :root pseudo class we can overcome this problem and reuse both padding and color wherever we need to. Our updated CSS looks like this:

:root {
    --primary-color: #fff;
    --primary-padding: 1rem
}

.card-wrapper { padding: var(--primary-padding); display: flex; flex-direction: column } .card { border: 1px solid #0068d8; margin-bottom: 0.5rem } .card-title { padding: var(--primary-padding); background-color: #007bff; color: var(--primary-color) } .card-body { padding: var(--primary-padding); background-color: #76b8ff; color: var(--primary-color) }

The HTML remains the same, and after opening the page in your browser, the result should be the same.

Inheritance

CSS variables can inherit its value like any other CSS property. If no value is set for it on an element, the value of its parent is used. Let's update our CSS to reflect this:

:root {
    --primary-color: #fff;
    --primary-padding: 1rem
}

.card-wrapper { padding: var(--primary-padding); display: flex; flex-direction: column } .card { border: 1px solid #0068d8; margin-bottom: 0.5rem } .card-title { --primary-padding: 1.5rem; --primary-color: red; padding: var(--primary-padding); background-color: #007bff; color: var(--primary-color) }
.card-body { padding: var(--primary-padding); background-color: #76b8ff; color: var(--primary-color) }

Now, if we run the page in the browser, the result should be that each card header has its padding and color set to 1.5rem and red, respectively, instead of the values defined on the :root pseudo class. This means that all elements have inherited their color and padding from the parent (in this case the :root pseudo class) except of the card header.

Default (fallback) Values

CSS variables do support the default or fallback values, meaning that we can define what value we want to use if the custom CSS variable fails. This is done by passing the second parameter to the var function. The given value will be used as a substitute when the CSS variable is not defined. Let's update the CSS to reflect this:

:root {
    /--primary-color: #fff; a fallback value is used instead of this variable/
    --primary-padding: 1rem
}

.card-wrapper { padding: var(--primary-padding, 1rem); display: flex; flex-direction: column } .card { border: 1px solid #0068d8; margin-bottom: 0.5rem } .card-title { --primary-padding: 1.5rem; --primary-color: red; padding: var(--primary-padding, 1rem); background-color: #007bff; color: var(--primary-color, #fff) }
.card-body { padding: var(--primary-padding, 1rem); background-color: #76b8ff; color: var(--primary-color, #fff) }

The output should, again, be the same since we've defined the white color as the fallback value. Play around with it a little bit to see the effect.

Invalid Values

If the CSS variable has been defined with an invalid value the browser will set the initial or the parent value for the given property.

First, it will check if the property is inheritable, if it is, it will take the value from the parent (if the element has one). If the element doesn't have a parent, the default initial value for the property will be used. Let's update the card wrapper and title classes to reflect this behaviour:

...

.card-wrapper { padding: var(--primary-padding); display: flex; flex-direction: column; color: orange /* assign a new color here / } .card-title { --primary-padding: 1.5rem; --primary-color: 1px; / assign an invalid value here */ padding: var(--primary-padding, 1rem); background-color: #007bff; color: var(--primary-color, #fff) }

...

Now, if we run the page in the browser, card headers will have a color changed to orange

Dynamic Usage (JavaScript)

CSS variables can be accessed from the JavaScript dynamically. We can get or set its value like for any other property:

const el = document.querySelector(':root');

// get the value const padding = el.style.getPropertyValue('--primary-padding');

// set the value el.style.setProperty('--primary-padding', '3rem');

Thank for reading. Originally published on https://dev.to/

css web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire CSS Developer

Want to develop a website or re-design using CSS Development? We build a website and we implemented CSS successfully if you are planning to **[Hire CSS Developer](https://hourlydeveloper.io/hire-dedicated-css-developer/ "Hire CSS Developer")**...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Developing for the Mobile-Web: Part 1 — CSS Media Queries

Developing our web pages for the mobile web has never been more important than it is now. I grew up in the early stages of the internet.