A Beginner's Guide to CSS Variables

Published on Jan 10, 2024
5-minute read

This article is a beginner-friendly introduction to an advanced Cascading Style Sheets (CSS) concept— CSS variables. CSS variables make your CSS code cleaner and easier to maintain. This article will focus on the following four topics:

  • Declaring a CSS variable.
  • Using a CSS variable.
  • Global and local scopes of CSS variables.
  • Overriding a global CSS variable with a local CSS variable.

This article is for web designers and developers who are comfortable with the fundamental CSS concepts such as CSS Syntax, CSS Selectors, and CSS Properties.

Declaring a CSS variable

To declare a CSS variable, use -- followed by a variable name inside a CSS selector.

selector {
 --background-light: #FAFAFA;
}

In the above code, background-light is the variable name, --background-light is the CSS variable, and #FAFAFA is the value assigned to the CSS variable.

Note: CSS variables are case-sensitive. This means --background-light and --Background-light are two different CSS variables.

Using a CSS variable

To use the above declared CSS variable, --background-light , insert it inside the var() function of a CSS selector.

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

In the above code, the background-color property of the body element takes the value of --background-light variable using the var() function. In simpler terms, the background color of the body element will be set to #FAFAFA.

Global and local scopes of CSS variables

A global CSS variable is declared inside the :root pseudo-selector and can be used throughout the stylesheet document. A local CSS variable is declared inside a particular CSS selector and can be used only inside that selector.

The following code demonstrates the declaration of the global variable, --background-light , inside the :root pseudo-selector. It is then used inside the body selector:

/* Declaring a global CSS variable */
:root {
 --background-light: #FAFAFA;  
}

/* Using the global CSS variable */
body {
 background-color: var(--background-light);  
}

The following example demonstrates the declaration and usage of the local variable, --background-light:

/* Declaring and using a local CSS variable */
body {
 --background-light: #FAFAFA;
 background-color: var(--background-light);  
}

Overriding a global CSS variable with a local CSS variable

Override a global CSS variable with a local CSS variable by re-declaring the CSS variable within a specific selector you want modified.

The following example demonstrates the overriding of a global CSS variable --background-light inside the button selector:

:root {
 --background-light: #FAFAFA;  
}

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

button {
 --background-light: #D5D5D5;  /* local CSS variable overrides global CSS variable */
 background-color: var(--background-light);
 color: #141414;
 padding: 1rem;  
}