iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Variables

CSS custom properties — usually called variables — let you store a value once and reuse it everywhere. They live in the cascade, so they can be re-themed at runtime.

Defining and using

CSS
:root {
  --brand:    #04AA6D;
  --radius:   6px;
  --spacing:  1rem;
}

.button {
  background: var(--brand);
  border-radius: var(--radius);
  padding: calc(var(--spacing) / 2) var(--spacing);
}

The convention is to declare global variables on :root (the <html> element). Any descendant can read them with var(--name).

Why use them

BenefitWhat it lets you do
DRYChange one declaration instead of fifty.
ThemingToggle dark mode by overriding the variables, not the components.
RuntimeJavaScript can read & write them — animate hue, contrast, scale.
ScopingRe-declare a variable on a parent to retheme just that subtree.
Fallbacksvar(--brand, #04AA6D) uses the second value if the variable isn't set.

Dark mode in five lines

CSS
:root          { --bg: #fff; --fg: #111; }
[data-theme="dark"] { --bg: #111; --fg: #eee; }

body { background: var(--bg); color: var(--fg); }
Tip: Variables and specificity are independent — var() resolves before the cascade picks a winning rule. That's what makes per-component theming so clean.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Variables</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Use the brand custom property as the background.

.btn { background: (--brand); }

Test yourself

Q1. How do you declare a CSS custom property?
Q2. How do you read a custom property?
Q3. Where do you typically declare global CSS variables?

Discussion

Loading…