Ad space (banner)
🎨HTML & CSS Lessons
Lesson 11 / 50

CSS Variables (Custom Properties)

In this lesson you'll learn how to use CSS variables (custom properties) so you can manage your design in one place. This is for people searching "CSS variables usage" or "CSS custom properties."

Registering a color or size as a "CSS variable" with --variableName: value; lets you reuse it with var(--variableName). This is very handy when you want to change your design all at once — fixing the theme color in one spot unifies the color across the whole site. Defining it on the :root selector makes it a variable usable across the entire page.

The sample code defines two CSS variables, --main-color and --spacing, inside :root, and calls them within .box's style with something like var(--main-color). Picture how changing the value of --main-color in just one place would instantly change the color of every element that uses it.

A common beginner stumbling block is that a variable name must always start with -- (two hyphens). Forgetting this makes it indistinguishable from a normal property, and it won't work correctly. Forgetting var() on the calling side is another easy mistake to make, so it's worth remembering the two together.

This brings the same idea as a "variable" in a programming language into CSS, and it's a mechanism that dramatically improves maintainability the larger a site gets. This idea also becomes the foundation when implementing a feature to switch themes, like dark-mode support.

HTML & CSS
OUTPUT

💡 The preview runs entirely on this page — nothing is sent externally.

Ad space (banner)
Ad space (in-article)