Hello Sunil
css-variables-feature-image

CSS Variables – A Quick Start Guide

CSS Variables, also known as CSS custom properties, are gaining popularity for their powerful features and dynamic adaptability.

Unlike traditional CSS, they reduce repetition and can be updated on-the-fly without preprocessors.

In this guide, we’ll explore how to use them effectively to simplify your CSS workflow. Ready to get started? Let’s go!

What are CSS variables?

CSS variables store information that you can use again and again in your stylesheets. They help to avoid repeating the same things over and over.

For example, if you have specific colors you use a lot in your web app, you can store them in variables. This makes it easier to keep things looking consistent.

Normally, if you wanted to change a color, you’d have to go through all your CSS and change it everywhere. But with variables, you only need to change it in one place. This saves time and reduces mistakes.

How to define and use CSS variables

To create a CSS variable, just add two dashes (--) before the variable name. For example, if you want a variable for the mainColor, you could name it --mainColor and give it a value like limegreen.

So, in CSS, it looks like this:

body {
    --mainColor: limegreen;
}

Once you’ve declared a variable in CSS, you can use it by using the var() function.

This function retrieves the value of the variable and replaces itself with that value. So, to use a variable, just write var() and put the variable name inside the parentheses.

In this example, the div element uses the var() function to get the value of the mainColor variable. So, when the browser sees var(--mainColor), it replaces it with the actual color value, which is limegreen.

body {
    --mainColor: limegreen;
}

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

In other words, the CSS code would translate to this:

body {
    --mainColor: limegreen;
}

div {
    color: limegreen;
}

Nested CSS variables

With nested CSS variables, you can make one variable’s value depend on another variable.

For example:

:root {
  --top-color: orange;
  --bottom-color: yellow;
  --my-gradient: linear-gradient(var(--top-color), var(--bottom-color));
}

Here, --my-gradient is set as a gradient using the values of --top-color and --bottom-color.

So, if you change --top-color or --bottom-color, the gradient defined by --my-gradient automatically updates everywhere it’s used.

This simplifies managing gradients in your stylesheets.

Fallback value & CSS variables

You can add fallback values to your CSS variables.

For example:

var(--mainColor, #333);

In the example above, #333 is a fallback value. Fallbacks are there in case the CSS variable is invalid or unset. Without fallbacks, if a variable isn’t set or is invalid, the browser will use the inherited value instead.

Scope of CSS variables

CSS variables can be defined anywhere in a stylesheet, but their access can be limited to specific code blocks, known as scopes. There are two types of scopes for variables in CSS: Global and Local.

  • Global scope: Variables declared globally are available for use throughout the entire stylesheet.
  • Local scope: Variables declared locally can only be used within the code block where they are declared.

Global scope

To make a CSS variable available globally, declare it within the :root pseudo-class, which targets the highest-level element in the HTML document (usually the <htmL> tag).

This ensures the variable is accessible throughout the entire stylesheet since all DOM elements are descendants of the <htmL> tag.

Consider the example below:

<body>
    <div class="container">
      <h2>Lorem Ipsum</h2>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper
        diam at erat pulvinar, at pulvinar felis blandit.
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper
        diam at erat pulvinar, at pulvinar felis blandit.
      </p>
      <p>
        <button>Yes</button>
        <button>No</button>
      </p>
    </div>
</body>
:root {
  --raspberry: #d21f3c;
  --white: #ffffff;
}

body {
  background-color: var(--raspberry);
}

h2 {
  border-bottom: 2px solid var(--raspberry);
}

.container {
  color: var(--raspberry);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--raspberry);
  border: 1px solid var(--raspberry);
  padding: 5px;
}

In the provided example, we define two global variables (--raspberry and --white) within the :root pseudo-class, and then use the var() function to apply these variables later in the stylesheet.

This approach simplifies styling and ensures consistency across the entire webpage.

Output:

CSS Variables - Global scope - img 1

Local scope

In this example, we are going to learn about local variables, which are only accessible within specific parts of the stylesheet. Unlike global variables, local variables are declared inside the selector where they’re used.

For instance, if we want buttons to have a different shade of red, we can redefine the --raspberry variable inside the button selector.

This local --raspberry variable will then be used only within the button selector, overriding the global --raspberry variable.

:root {
  --raspberry: #d21f3c;
  --white: #ffffff;
}

body {
  background-color: var(--raspberry);
}

h2 {
  border-bottom: 2px solid var(--raspberry);
}

.container {
  color: var(--raspberry);
  background-color: var(--white);
  padding: 15px;
}

button {
  /*Overriding global variables With local variables*/
  --raspberry: #890020; 
  background-color: var(--white);
  color: var(--raspberry);
  border: 1px solid var(--raspberry);
  padding: 5px;
}

By doing this, we can tailor variables to specific elements without affecting the rest of the stylesheet. This provides more control and flexibility in styling individual components.

Output:

CSS Variables - Local scope - img 1

If a variable is to be used only one single place, we could also have declared a new local variable at button selector, like this:

:root {
  --raspberry: #d21f3c;
  --white: #ffffff;
}

body {
  background-color: var(--raspberry);
}

h2 {
  border-bottom: 2px solid var(--raspberry);
}

.container {
  color: var(--raspberry);
  background-color: var(--white);
  padding: 15px;
}

button {
  /*Add a new local variable*/
  --btn-black: #000000;
  background-color: var(--white);
  color: var(--btn-black);
  border: 1px solid var(--raspberry);
  padding: 5px;
}

Output:

CSS Variables - Local scope - img 2

Conclusion

In conclusion, CSS variables offer numerous advantages in web development, such as reducing repetition, enhancing maintainability, and providing greater flexibility in styling.

By leveraging global and local scopes, developers can efficiently manage styles across their projects while customizing elements as needed.

We encourage you to implement CSS variables in your projects to experience these benefits firsthand. If you found this blog helpful, please share your feedback and don’t hesitate to reach out with any questions or concerns.

Happy coding!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.