CSS Variables – What Are They & How to Use Them
Tags: css, tutorial, programming, beginners
Published: 2022-11-22 13:40:00

# What Is a CSS Variable?
CSS custom properties are often referred to as CSS variables. They allow you to set and store values within them for use throughout your stylesheet(s). For example, you could have a primary-color variable that is set to the hex value of red (#FF0000).

# What Are CSS Variables Used for?
CSS variables allow you to use a value throughout your stylesheet without the need for typing it in repeatedly. Modifying the value of a variable updates all the places in your stylesheet where the variable was used, preventing the need to go back and edit several instances of the same value in the future.*

For example, if the primary color of your website is red (#FF0000), then you'd have several places throughout your CSS that would need to be set to #FF0000. If, in the future, the primary color of the website was to change to blue (#0000FF), you'd have to go through your stylesheet and update every instance where red was used, manually. With CSS variables you'd only have to change the variable's value for it to update throughout the stylesheet.

_There are some exceptions to this, especially when a variable's value is set in multiple locations. Example 3 below covers this in more detail._

# How to Set Up and Use a CSS Variable
Like other programming languages, CSS variables need to be declared with a valid name and an appropriate value before they can be used. Once declared their value can be called upon by using the var() function throughout the scope (global or local) in which the variable was declared. CSS variables can be declared both globally and locally as needed.

## Global Versus Local CSS Variables
A CSS global variable is declared such that it can be used throughout your styles, this includes the stylesheet in which the variable was declared, but also other stylesheets (other files) as well. An example of this can be found on [StackOverflow](https://stackoverflow.com/questions/45581135/are-css-custom-properties-global-across-linked-css-documents). As for a local variable, they're declared on a smaller scope than global, commonly on a specific class, or ID. The variable cannot be used outside the local scope in which it was declared.

The image below shows an example of how a local CSS variable works.

* The variable _primary-color_ is set to red and is declared locally on the featured class.
* The color property is then set to the value of _primary-color_ on all paragraphs (p elements).
* The output shows, that the red color is exclusively applied to the paragraphs that are contained by the div with the _featured_ class and not any other paragraphs.

![3 Paragraph CodePen Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w3p0n0ggm2he5qoz7vu4.jpg)

_If you're a little confused by this example, don't worry, we have more explanations and three detailed examples still coming up!_


# How to Declare a CSS Variable
CSS variables are declared by using two dashes (--) followed by a valid variable name. Remember, they can be declared both globally and locally.

![CSS variable declartion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dvia0khvya0iaz5d3721.png)

## Valid CSS Variable Names
CSS variable names can contain:
* alphanumeric characters
* dashes
* underscores

You can see an example of the same "primary color" variable declared with variety of character configurations in the image below.

![Valid CSS variable names](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2gig4hvslg6sfgy7hp7m.png)

## How to Declare a CSS Variable Globally
To declare a CSS variable globally, we use the :root pseudo-class. Since we are working with HTML, the :root pseudo-class applies to the HTML element, and therefore globally throughout our page.

![Declare global CSS variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78hb9l313k9z635xged9.png)

## How to Declare a CSS Variable Locally
To declare a CSS variable locally, we declare the variable in a desired scope - like a class, or an ID. Once delcared locally, the variable can only be used within that scope.

![Declare local CSS variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oyup4v9e42v34lbp3959.png)

## How to Use a CSS Variable
To use a CSS variable in your stylesheet, you need to use the var() function. The var() function inserts the variable's value wherever it is used. Simply enter the variable name between the brackets like so, var(--variablename). Remember you need to declare your variable before using it.

![CSS Var Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1l994k1edcg0y3hgqtmt.png)

# CSS Variable Examples
Below are some detailed examples of how global and local CSS variables work.

## Example 1 - The Global Scope
In this example, you can see that we've globally declared the red-text variable and then applied it's value to the color property, which is being applied to all paragraph elements.

![Example 1 CodePen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qvk6hiwcp0dqebm1rhyv.jpg)

As you can see in the image above, all the paragraphs have red text because the red-text variable was declared globally and applied to all paragraphs. Remember that global variables can be used throughout your CSS stylesheets, this includes across multiple files (ie variables.css, styles.css, etc.).

### Example 1 Breakdown
In our HTML we have two paragraph elements...

1. Paragraph 1 is contained within a div that has the _featured_ class applied to it.
2. Paragraph 2 is NOT contained within the div with the _featured_ class

![Example 1 HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fz5lfp02boh00swpews6.png)

In our CSS we have three aspects to focus on...

1. The _red-text_ variable is being declared on the _:root_ pseudo-class (which is the same as declaring it on the HTML element)
2. The _color_ property is being set to the value of the red-text variable
3. The _color_ property mentioned above is being applied to all paragraphs (p tags) in the HTML

![Example 1 CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7mt2c984lqkyqe2lty7.png)

In our output/webpage we can see that both Paragraph 1 and Paragraph 2 have red text. Despite Paragraph 1 being contained within a div, and Paragraph 2 being a direct child of the HTML element, the value of the _red-text_ variable applies. The red-text variable is global and therefore applies not just to direct children of the HTML element, but throughout other scopes that may be present - like the _featured_ class scope that Paragraph 1 finds itself in.

![Example 1 Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylszoq51yantdyhl8oqb.jpg)

## Example 2 - The Local Scope
In this example, you can see that we've locally declared the _red-text_ variable on the _featured_ class. This means that the value of _red-text_ can only be applied to elements that are within the scope of the _featured_ class.

![Example 2 CodePen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ey2i5hamt7cc1uaqh36k.jpg)

As you can see above, we have a div and two paragraphs. The div has the _featured_ class applied to it. In our CSS we're applying the _red-text_ variable to the color property on all paragraphs, but the second paragraph's text did not change color. This is because the second paragraph is not within the scope of the _featured_ class.

### Example 2 Breakdown
In our HTML we have two aspects to focus on...

1. Paragraph 1 is contained within a div that has the _featured_ class applied to it
2. Paragraph 2 is NOT contained within the div with the _featured_ class

![Example 2 HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/474j5z3xo8ydzzhw02gz.png)

In our CSS we have three aspects to focus on...

1. The _red-text_ variable is being declared on the _featured_ class
2. The _color_ property is being set to the value of the _red-text_ variable
3. The _color_ property mentioned above is being applied to all paragraphs (p tags) in the HTML

![Example 2 CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jh8znwxs08ij0kcz7vdv.png)

In our output/webpage, we can see that only Paragraph 1 is showing red text, when in fact we've applied the _red-text_ variable's value to the color property on all paragraph HTML elements.

![Example 2 Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5ytcbzz5h1xmk3xgz6q.jpg)

The reason Paragraph 2 does not have red text, is because we've declared the _red-text_ variable locally, on the _featured_ class's scope. Paragraph 2 falls outside of this scope and therefore the value of the _red-text_ variable does not apply.

Let's build on what we've learned here with Example 3 below.

## Example 3 - Local & Global
In this example we're going to combine the use of both globally and locally declared variables at the same time, with a bit of a twist - we'll be declaring the same variable twice, in both the local and global scopes.

![Example 3 CodePen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1f82zbg6gk8d2n94633.jpg)

As you can see above, we've declared two variables, in three different instances:

* _text-color_ is declared globally and is set to the hex value _#FF0000_ (red)
* _text-size_ is declared globally and is set to _25px_
* _text-color_ is declared again, locally under the scope of the featured class, set to the hex value _#0000FF_ (blue)

The final result is that Paragraph 1 has blue text, from the locally declared version of the text-color variable. Paragraph 1 also has larger text than Paragraph 2, because its font-size is being set to 25px by the _text-size_ variable. Paragraph 2 has blue text because its color property is being set by the globally declared version of the text-color variable.

### Example 3 Breakdown
Just like Example 2, in our HTML we have two aspects to focus on...

1. Paragraph 1 is contained within a div that has the _featured_ class applied to it.
2. Paragraph 2 is NOT contained within the div with the _featured_ class

![Example 3 HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ix5t8tp854rdms5lx1cx.png)

For the CSS we have a few aspects to focus on...
1. _text-color_ is declared globally as the color red
2. _text-size_ is declared globally as the value 25px
3. _text-color_ is declared again, but locally this time as the color blue

![Example 3 CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/966guxbn6zm4quljpsah.png)

And finally, our output/webpage for this example displays as you can see in the image below. Paragraph 1 is larger and is blue, while Paragraph 2 is the default font size and is red.

![Example 3 Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6p1gu9qw86f6rkpdsmp8.jpg)

Let's break down this output piece-by-piece:

* **Paragraph 1** is larger than the default font size due to the _text-size_ variable being applied to the featured class
* **Paragraph 2** is red because the value of the _text-color_ global variable is being applied to all paragraphs
* Despite _text-color_ being applied to all paragraphs, **Paragraph 1** is not red, instead it shows up as blue. This is because we've declared the _text-color_ variable again locally in our CSS on the _featured_ class. The local declaration is more specific to Paragraph 1 than the global declaration, and therefore the local declaration wins out. You can read a little more about cascading and specificity with variables in [this DEV article](https://dev.to/nirazanbasnet/understanding-css-variables-4cj0)

# Theming a Website With CSS Variables
In this article we focused on CSS variable basics, but I think it's important to showcase some real-world applications of CSS variables so that you can see them in a more practical setting. One of the most common real-world uses for CSS variables is theming a website with a different colour scheme based on a set of parameters, such as toggling between a light and dark mode.

Toggling between dark and light modes is a popular option for a lot of software out there, including websites and web apps. Using CSS variables alongside additional HTML, CSS, and JS, you can put together a practical theme switcher. [Ananya Neogi](https://dev.to/ananyaneogi) was able to make a dark/light mode toggle switch - detailed guide in this article: [Create A Dark/Light Mode Switch with CSS Variables](https://dev.to/ananyaneogi/create-a-dark-light-mode-switch-with-css-variables-34l8)

Similarly, Praveen on the Tech Inscribed blog, has a guide for making a theme selector with a focus on a light/dark theme in this guide: [Developing Websites with Multiple Themes using CSS Variables](https://techinscribed.com/multiple-themes-using-css-variables/)

# Sources
* Free CSS variables course ([Scrimba](https://scrimba.com/learn/cssvariables))
* Using CSS custom properties (variables) ([MDN Docs](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties))
* CSS Variables - The var() Function ([W3Schools](https://www.w3schools.com/css/css3_variables.asp))
* Understanding CSS Variables ([DEV](https://dev.to/nirazanbasnet/understanding-css-variables-4cj0))