Most websites use CSS to polish their appearance and style different web page components. CSS, or Cascading Style Sheet, is not technically a programming language. However, CSS can be used with programming languages like JavaScript to create responsive and interactive web pages.
If you have used programming languages, such as JavaScript, you know that you can declare a variable, assign it a value and reuse it in various parts of your code. The good news is that you can apply the same concept in CSS.
This article will define CSS variables, describe their benefits, and show you how to declare and use a variable in CSS.

What are Variables in CSS?
CSS variables are custom properties that allow web developers to store values they can reuse through the stylesheet. For instance, you can declare the font style, background color, and font size that you can reuse with elements such as headings, paragraphs, and divs in your codebase.
Why use CSS variables? These are some of the reasons;
- Makes it easier to update code: Once you declare a variable, you can reuse your entire stylesheet without updating every element manually.
- Reduces repetition: As your codebase grows, you will find that you have similar classes and elements. Instead of writing CSS code for every item, you can simply use CSS variables.
- Makes your code more maintainable: Code maintenance is important if you want your business to be a going concern.
- Improves readability: The modern world encourages collaboration. Using variables in CSS results in a compact codebase that is readable.
- Easy to maintain consistency: CSS variables can help you maintain a consistent style as your source code grows or app-size increases. For instance, you can declare the margins, padding, font style, and colors to be used in your buttons across the website.
How to Declare Variables in CSS
Since you know understand what variables in CSS are and why you should use them, we can go ahead and illustrate how to declare them.
To declare a CSS variable, start with the element’s name, then write two dashes (–), the desired name and value. The basic syntax is;
element {
--variable-name: value;
}
For instance, if you want to apply padding in your entire document, you can declare it as;
body {
--padding: 1rem;
}
Scope of Variables in CSS
CSS variables can be scoped locally (accessible within a specific element) or globally (accessible in the entire style sheet).
Local variables
Local variables are added to specific selectors. For instance, you can add them to a button. This is an example;
.button {
--button-bg-color: #33ff4e;
}
The background color variable is available on the button selector and its children.
Global variables
Once declared, you can use global variables with any element in your code. We use the :root
pseudo-class to declare global variables. This is how we declare them;
:root {
--primary-color: grey;
--secondary-color: orange;
--font-weight: 700:
}
In the above code, you can use any of the variables declared with different elements, such as headings, paragraphs, divs, or even the entire body.
How to use Variables in CSS
We shall create a project for demonstration purposes and add index.html and styles.css files.
In the index.html
file, we can have a simple div with two headings ( h1
and h2
) and a paragraph (p
).
<div>
<h1>Hello Front-end Dev!!!!</h1>
<h2>This is how to use variables in CSS.</h2>
<p> Keep scrolling</p>
</div>
In the style.css
file, we can have the following;
:root {
--primary-color: grey;
--secondary-color: orange;
--font-weight: 700:
--font-size: 16px;
--font-style: italic;
}
body {
background-color: var(--primary-color);
font-size: var(--font-size);
}
h1 {
color: var(--secondary-color);
font-style: var(--font-style)
}
h2 {
font-weight: var(--font-weight)
}
p {
font-size: calc(var(--font-size) * 1.2);
}
When the web page is rendered we will have the following;

From the code above, we have declared global variables in the :root
element. We must use the var keyword to use the global variable in any of our elements. For instance, to apply the background color we declared as a global variable, we present our code as follows;
background-color: var(--primary-color);
Check all the other elements, and you will note a trend in how the var
keyword is applied.
Use CSS Variables with JavaScript
We will use local and global variables to illustrate how to use CSS variables with JavaScript.
We can add an alert element to our existing code;
<div class="alert">Click me!</div>
Our new index.html
document will be as follows;
<div>
<h1>Hello Front-end Dev!!!!</h1>
<h2>This is how to use variables in CSS.</h2>
<p> Keep scrolling</p>
</div>
<div class="alert">Click me!</div>
We can style our variable. Add the following code to your existing CSS code;
.alert {
--bg-color: red; /* Define local variable */
background-color: var(--bg-color); /* Use the local variable for the background color */
padding: 10px 20px;
border-radius: 4px;
font-weight: var(--font-weight); /*Use the global variable for font weight*/
width: 50px;
}
We have done the following;
- Defined a local variable inside the alert element;
--bg-color: red
- Used the var keyword to access this local variable;
background-color: var(--bg-color);
- Used the global variable we declared earlier as our font-weight;
font-weight: var(--font-weight);
Add JavaScript code
We can make our alert element responsive; when you click it, you get a pop-up on your browser which says; “We have used CSS Variables with JavaScript!!!!”.
We can add JavaScript code directly to the HTML code by enclosing it using <script/>
tags. JavaScript code should come after HTML code, but before closing the </body>
tag.
Add this code;
<script>
const alertDiv = document.querySelector('.alert');
alertDiv.addEventListener('click', function() {
window.alert("We have used CSS Variables with JavaScript!!!!");
});
</script>
Your HTML code should now look something like this;

Our JavaScript does the following;
- We use
document.querySelector()
to locate the alert element. - We assign the alert element a variable
alertDiv
. - On the alertDiv, we use
addEventListener()
method to add a ‘click’ event. - We use the
window.alert()
to display a message when the click event happens.
When the page is rendered, you will have the following;

When you click the alert
, you get the following;

Fallback Values in CSS Variables
What happens when you reference a variable not defined in your stylesheet? The CSS effect you intend to apply will not be applied. Fallback values offer a value of an effect that will appear instead of the unreferenced variable.
Fallback values are useful in the following ways;
- If certain browsers don’t understand CSS variables, the select property can have something to fall back to.
- If you suspect a page is not working as expected due to a CSS variable, you can use a Fallback value to test if it is true.
You can have more than one fallback property, separated by commas. Take this code, for instance;
:root {
--primary-color: #007bff;
}
.btn {
background-color: var(--primary-color, red, yellow);
padding: 10px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
If you misspell the word primary-color
when using the global variable, which means it is undeclared, it will pick red, the Fallback value.
We can demonstrate it better with this code;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
:root {
--primary-color: #007bff;
}
.btn {
background-color: var(--primary-color, red);
padding: 10px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button class="btn">Click me!</button>
</body>
</html>
If you render it on the browser, you get this;

However, we can get the same code and change just one character on the button
selector as follows;
.btn {
background-color: var(--primary-colr, red); /*I have misspelled primary-color to be primary-colr */
padding: 10px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
The browser will now render this;

Use Dynamic Value and Calculated Value Variables in CSS
Dynamic values are updated automatically based on certain events or conditions, such as user inputs.
Study this code;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSS Variables with JavaScript</title>
<style>
:root {
--color: #333;
}
#color-input {
margin-left: 1em;
}
#color-input {
--color: var(--color-input);
}
</style>
</head>
<body>
<label for="color-input">Choose a color:</label>
<input type="color" id="color-input">
</body>
</html>
The above code does the following;
- We declare a variable
--color
with a default value of#333
using the:root
selector. - We use
#color-input
to select the input element. - The value of
--color
is set tovar(--color-input)
, which means the color always updates when the user picks a new color using the color picker.
Calculated values perform calculations based on other properties or variables. We can illustrate it using this code;
:root {
--base-font-size: 14px;
--header-font-size: calc(var(--base-font-size) * 3);
}
h2 {
font-size: var(--header-font-size);
}
From this code block, we can note the following;
- We have
--base-font-size
variable that defines the base font size. - We have
--header-font-size
, which is 3 times the value of –base-font-size. - We have a
h1
selector that usesvar
with--header-font-size
. - So, all the
h1
in the web page will be thrice the size of--base-font-size
.
Wrapping Up
You now understand how to use CSS variables to speed up the development process and write code that is easy to maintain. You can use custom variables with HTML and libraries such as React. Check out different approaches you can use to style React using CSS.
You can check the source code here.