Skip to main content

CSS Variables

Inserting the value of a CSS variable is the job of the var() function.

Because CSS variables have access to the DOM, their scope can be local or global, JavaScript can change them, and media queries can change them too.

The colors of your design are a natural fit. Put each color in a variable once rather than copying and pasting it over and over.


CSS Declare a Variable

A CSS variable has either global or local scope.

A global variable is reachable from anywhere in the document; a local one works only inside the selector that declares it.

For global scope, place the declaration inside the :root selector, which matches the document's root element.

For local scope, place it inside the selector that will use it.

Names always start with two dashes (--), and upper and lower case count as different!

Variable declaration syntax

The :root block holds a global variable, and a specific selector holds a local one.

styles.css
:root {
  --primary-bg-color: green; /* global scope */
}

.note {
  --note-bg: yellow; /* local scope */
}

The CSS var() Function

Once a CSS variable has been declared, var() inserts its value.

Two arguments are possible: the variable name, which is required and starts with two dashes, and a fallback value, which is optional and steps in when the variable cannot be found.

Working with var() brings these advantages:

  • Maintenance gets simpler, since updates are easier
  • The code reads more clearly and is more understandable
  • Color values across the entire page are easier to change

var() syntax

How var() is written: name must be given, while value is an optional fallback.

styles.css
var(--name, value)

CSS Variables Example

Two global variables are declared first, --primary-bg-color and --primary-color. Further down the style sheet, var() brings in their values.

Blue theme variables

The two global CSS variables hold blue and white here, and var() passes those values to the body, the container, the heading and the note elements.

Prompt
Create a page that declares two global CSS variables (--primary-bg-color as #1e90ff and --primary-color as #ffffff) in :root. Use them with var() to style the body background, a container with text color, background, padding, an h2 with a bottom border, and a note div with a border and padding.
Output: complete HTML page

Green theme variables

Editing just those two variable values is all it takes to restyle the entire page. Here they hold green and floral white.

Prompt
Create a page that declares two global CSS variables (--primary-bg-color as #8FBC8F and --primary-color as #FFFAF0) in :root. Use them with var() to style the body background, a container with text color, background, padding, an h2 with a bottom border, and a note div with a border and padding. This demonstrates how changing variable values changes the entire look.
Output: complete HTML page

CSS var() Function

To insert a CSS variable's value, call var().