You declare a CSS variable (a “custom property”) inside a CSS rule by giving it a name that starts with -- and assigning it a value, then you consume it with var(...):

css

:root {
  --main-color: #3498db;
  --padding-md: 1rem;
}

button {
  color: var(--main-color);
  padding: var(--padding-md);
}

What a CSS variable is

  • A CSS variable is a custom property whose name starts with -- (two dashes).
  • It holds a reusable value such as a color, size, or any other valid CSS value.

Example of the raw declaration syntax:

css

--css-variable-name: some-css-value;

You never write this on its own; you place it inside a selector.

Declaring global vs local variables

  • To declare a global CSS variable that works across your whole page, put it on :root (the document’s root element).
css

:root {
  --primary-color: #ff5722;
  --font-base-size: 16px;
}
  • To declare a local CSS variable, define it inside the specific selector that will use it.
css

.card {
  --card-border-radius: 12px;
  border-radius: var(--card-border-radius);
}

In this example, --card-border-radius is only available inside .card and its descendants.

Using a CSS variable with var()

Once declared, you read the value with the var() function:

css

.element {
  background-color: var(--primary-color);
  font-size: var(--font-base-size);
}

You can also provide a fallback value if the variable is missing or invalid:

css

.button {
  color: var(--button-text-color, #ffffff);
}

Here, #ffffff is used if --button-text-color isn’t set.

Tiny “real” example

Imagine you want consistent theming:

css

:root {
  --bg: #121212;
  --fg: #f5f5f5;
  --accent: #ff9800;
}

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

a {
  color: var(--accent);
}

You’ve just declared a small design system; switch the theme by changing the values under :root and everything updates automatically.

TL;DR:

  • Declare: selector { --name: value; } (e.g., :root { --main-color: #000; }).
  • Use: property: var(--name[, fallback]); (e.g., color: var(--main-color);).

Information gathered from public forums or data available on the internet and portrayed here.