Make Your Work Easier by Using Variables in CSS

Marilena

By Marilena

7 min read
Bookmark this post

Hello there! Today, we will analyze the amazing variables in CSS, also known as custom properties or cascading variables. It is a powerful technique that allows us to store reusable values for colors, sizes, fonts, and even animations. These values can be set once and used as many times as we want throughout our project.

Simply put, if we want to update a value through all our CSS code, we only need to change it in one place instead of searching and modifying multiple CSS rules. This keeps our code clean and organized and our work more flexible, especially in larger projects. 😎

How to declare CSS variables

CSS variables are defined using the -- prefix and are typically declared in the :root pseudo-class. Below, we can see an example with two declared variables. The first one refers to the --primary-color (main color) of our project, while the second one concerns the --text-font-size (text’s font size).

:root {
  --primary-color: purple;
  --text-font-size: 16px;
}
CSS

By defining variables in the :root pseudo-class, we make them accessible globally. To limit a variable’s scope, we can define it locally, within a specific selector, like a class or ID.

How to use CSS Variables

We connect these two variables with our CSS styles, using the var() function. This step is crucial for ensuring our variables will work correctly. Simple but super useful! 🤓 ✨

.body {
  background-color: var(--primary-color);
  font-size: var(--text-font-size);
}
CSS

Global VS local scope

Now, let’s examine what we mean by global and local variables and how knowing the difference between these two types of variables can help us write more flexible, organized, and efficient code.

Global and local variables in CSS are essential for keeping styles easily managed. Global variables, defined in the :root selector, can be used in any CSS rule in the entire stylesheet, creating consistent layouts. In contrast, local variables, declared inside a class or ID selector, are scoped only to specific elements and their children, allowing for a more customized styling.

Understanding variable scope with an example

Global type

We create two global variables named --primary-color and --secondary-color that can be applied everywhere in the stylesheet.

/* Anything inside :root is accessible globally */
:root {
  --primary-color: pink; 
  --secondary-color: gray;
}

body {
  background-color: var(--primary-color); /* Accessible here */
}

header {
  color: var(--secondary-color); /* Accessible here as well */
}
CSS

Local type

We create a local variable named --header-bg located inside the .header class. This specific variable can be applied only to the header and its descendants.

.header {
  --header-bg: gray; /* Local variable */
  background-color: var(--header-bg); /* Accessible here */
}

.header h1 {
  color: var(--header-bg); /* Accessible here */
}

.footer {
  background-color: var(--header-bg); /* Not accessible here, will not work */
}
CSS

Advanced CSS variable usage example

For better understanding, I’ve prepared a more detailed example of CSS variables, showing how to apply them in a stylesheet and an image to help visualize the results. We intend to create three identical boxes side by side within a container, all styled using CSS variables.

<div class="container">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
</div>
HTML
/* Container characteristics */
:root {
  --container-width: 600px;
  --container-height: 300px;
  --container-color: #3ab7b7; /* A shade of teal */
}

/* Box characteristics */
:root {
  --box-width: 150px;
  --box-height: 150px;
  --box-color: #fec0ca; /* A light shade of pink */
  --box-title-weight: 800;
  --box-title-size: 25px;
}


/* Box & Container border */
:root {
  --border-all-around: 5px solid;
}

body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  width: var(--container-width);
  height: var(--container-height);
  background-color: var(--container-color);
  border: var(--border-all-around);
  
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.box {
  width: var(--box-width);
  height: var(--box-height);
  background-color: var(--box-color);
  font-size: var(--box-title-size);
  font-weight: var(--box-title-weight);
  border: var(--border-all-around);
  
  display: flex;
  justify-content: center;
  align-items: center;
}
CSS

In the following image, we can see the layout we just created.

variables in css: A container with three identical boxes inside.

If we want to modify the height of our boxes, we can easily do it by changing only the --box-height variable. For example, let’s change it from 150px to 50px.

In the image below, we can notice the difference.

css variable: A container with three identical rectangles inside.

Naming variables can be a really demanding task! Keep names simple, but ensure they are clear and meaningful.

Combining multiple CSS variables

When working with variables, we have the flexibility to add many values inside a CSS property. Let’s try to create a rainbow effect. We have to define variables for each rainbow color (--color-red, --color-orange, --color-yellow, --color-green, --color-blue, --color-indigo, --color-violet). Then, we’ll apply them in linear-gradient to create the rainbow effect. 🌈 🎉

<div class="box"></div>
HTML
:root {
  --box-width: 800px;
  --box-height: 300px;
  --color-red: #ff0000;     /* Red */
  --color-orange: #ffa500;  /* Orange */
  --color-yellow: #ffff00;  /* Yellow */
  --color-green: #008000;   /* Green */
  --color-blue: #0000ff;    /* Blue */
  --color-indigo: #4b0082;  /* Indigo */
  --color-violet: #ee82ee;  /* Violet */
  --border-all-around: 5px solid;
}

.box {
  width: var(--box-width);
  height: var(--box-height);
  background: linear-gradient(
    to right,
    var(--color-red),
    var(--color-orange),
    var(--color-yellow),
    var(--color-green),
    var(--color-blue),
    var(--color-indigo),
    var(--color-violet)
  );
  border: var(--border-all-around);
}
CSS

In the following image, we can see the effect! Nice, isn’t it!?

CSS variable fallback: A rectangle with rainbow effect.

CSS Variable Fallback

We also have the flexibility to use fallbacks. But what is a fallback? 🤔
A fallback acts as a default value when:

  1. A variable is not defined, or
  2. the value of a variable is not valid.

Below are examples for each case to help you understand it better. 🧐
Case 1 – A variable is not defined
In the following example, the box will feature a dark gray background since --bg-color is not defined, resulting in the use of the fallback color.

<div class="box"></div>
HTML
:root {
  --box-width: 300px;
  --box-height: 300px;
  /* --bg-color is not defined */
  --border-all-around: 5px solid;
}

.box {
  width: var(--box-width);
  height: var(--box-height);
  background-color: var(--bg-color, darkgray); /* Fallback to darkgray */
  border: var(--border-all-around);
}
CSS

The image below displays the results.

css variables: A box with darkgray background color and a title with 40 pixels font size.

Case 2 – the value of a variable is not valid
The box will have a dark gray background because --bg-color is set to an invalid value; “pinky” is not a valid way to specify the color pink, so the fallback will be used instead.

:root {
  --box-width: 300px;
  --box-height: 300px;
  --bg-color: pinky; /* --bg-color is invalid */
  --border-all-around: 5px solid;
}

.box {
  width: var(--box-width);
  height: var(--box-height);
  background-color: var(--bg-color, darkgray); /* Fallback to darkgray */
  border: var(--border-all-around);
}
CSS
Legal characters for css variable names​: A box with darkgray background color.

Frequently Asked Questions 🤔

Are spaces allowed in css variable names?​

No, spaces are not allowed in CSS variable names. You can use hyphens (-), underscores (_), or camelCase instead.

CSS variable names can include letters, numbers, underscores (_), hyphens (-), and must start with two dashes (--). They cannot contain spaces or special characters.

🌼 Hope you found my post interesting and helpful. Thanks for being here! 🌼

DigitalOcean Referral Badge
guest
0 Comments
Inline Feedbacks
View all comments

Continue reading

Front, Programming

Learn How to Select Only the CSS First Child

Front, Programming

The CSS nth-of-type Selector – How To Target Elements By Type

Front, Programming

What You Need to Know About CSS nth child Selector – A Practical Guide

Front, Programming

CSS Selectors nth-child VS nth-of-type And How To Use Them Correctly

Front, Programming

Coding Made Easy With CSS Selectors: An Ultimate Guide

Front, Programming

How to Center in CSS Using Different Ways

Front, Programming

What You Need to Know About CSS Color Methods

Programming

Most Common Typescript Errors and How to Solve Them

Front, Programming

CSS Rainbow Text: How To Make Astonishing And Vibrant Fonts

Front, Programming

Most Useful HTML Elements for Maximizing Better Results

Back, Programming

Environment Variables 101: Secure Your Secrets Like a Pro

Front, Programming

HTML Formatting Elements Made Simple: With Easy And Practical Examples

Subscribe to our newsletter

Dive into the Fun Side of Tech! Posts, News, and More Delivered to Your Inbox!

Intuit Mailchimp