2 min read

CSS Variables (Custom Properties)

CSS Variables, officially known as Custom Properties, are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).

1. Why use CSS Variables?

  • Maintainability: Change a value in one place, and it updates everywhere.
  • Readability: --primary-brand-color is easier to understand than #ff4500.
  • Dynamic: Unlike preprocessor variables (Sass/Less) which compile to static values, CSS variables are live in the browser. They can be updated via JavaScript or media queries.

2. Syntax

Declaring a Variable

A custom property name must start with two dashes (--).

element {
  --main-bg-color: brown;
}

Using a Variable

Use the var() function to retrieve the value.

element {
  background-color: var(--main-bg-color);
}

3. Scope

CSS variables follow standard CSS cascading and inheritance rules.

Global Scope

To make a variable available globally, define it in the :root pseudo-class.

:root {
  --primary-color: blue;
}

h1 {
  color: var(--primary-color); /* Blue */
}

Local Scope

You can define variables inside specific selectors to limit their scope or override global values.

.card {
  --card-padding: 20px;
  padding: var(--card-padding);
}

.card-small {
  --card-padding: 10px; /* Overrides for .card-small */
}

4. Fallback Values

The var() function accepts a second argument as a fallback value, which is used if the custom property is invalid or undefined.

.box {
  /* If --box-color is not defined, use red */
  background-color: var(--box-color, red); 
}

5. JavaScript Interaction

You can read and modify CSS variables using JavaScript, enabling dynamic theming.

const root = document.documentElement;

// Get variable
const color = getComputedStyle(root).getPropertyValue('--primary-color');

// Set variable
root.style.setProperty('--primary-color', 'green');

6. Theming Example

CSS variables make implementing dark mode very easy.

:root {
  --bg-color: white;
  --text-color: black;
}

[data-theme="dark"] {
  --bg-color: black;
  --text-color: white;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

programming/css/css programming/css/css3 programming/javascript/vanilla/dom-manipulation