CSS Variables

CSS variables (custom properties) let you save a value, like a colour, in one place and use it many times. When you change it, it changes everywhere.


Define and use a variable

A variable name starts with two hyphens. Define it in :root (the whole page) and read it with var().

:root {
  --main-color: #0073aa;
  --space: 16px;
}

h1 { color: var(--main-color); }
.button {
  background: var(--main-color);
  padding: var(--space);
}
Output in the browser

Heading uses the variable

Button uses it too


Fallback value

p { color: var(--text-color, #333); }   /* #333 if --text-color is not defined */

Change a variable for one part (themes)

:root { --bg: #ffffff; --text: #222222; }

.dark {
  --bg: #1e1e1e;
  --text: #f5f5f5;
}

body, .card { background: var(--bg); color: var(--text); }
Output in the browser
This box uses the .dark values of the variables.

Variables can also be changed with JavaScript, which is how many sites build a dark mode switch.


Summary

  • Define with --name: value;, usually in :root.
  • Use with var(--name), and add a fallback if needed.
  • Change values inside a class to make themes.
  • Next: Transitions and Animations.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.