CSS Variables

A custom property — usually just called a CSS variable — lets you name a value once and reuse that name everywhere instead of retyping the raw value in every rule that needs it.

Declaring a variable

A custom property name always starts with two dashes. Declaring one on :root makes it available to every element on the page, since :root matches the top of the document and every element inherits from it:

Try it yourself
Result

var() and why one line beats a find-and-replace

var(--name) is how you read a custom property back out. The real payoff shows up once the same variable feeds several unrelated rules — change the single declaration and every rule using it updates together, instantly and consistently:

Try it yourself
Result

Change the one line in :root above to a different color and watch the button, the tag, and the sidebar line all update together. Without a variable, you'd have had to find and change that color in three separate places — and it's easy to miss one.

Fallback values

var() accepts a second argument to use if the variable isn't defined at all — handy for a component that should still work reasonably even when it's dropped somewhere that never set the variable it expects:

Try it yourself
Result

Redefining a variable in a smaller scope

A custom property isn't locked to :root — it can be redeclared inside any selector, and that new value only applies within that selector's scope, leaving the global default untouched everywhere else. This is how a lot of real "theme variants" work under the hood:

Try it yourself
Result

Notice the two cards share the exact same .card rule for background and text color — only the variables feeding it change. That's the core idea behind theming with CSS variables: write the rules once, and swap the values that feed them per section, per component, or per user preference like light/dark mode.

Note: a hardcoded color scattered across dozens of rules means dozens of places to hunt down when a design changes. The same color stored in one custom property means one change, applied everywhere it's used, with no chance of missing a spot.

Course complete

That covers the CSS course from top to bottom — linking a stylesheet, selectors, colors and backgrounds, the box model, typography, flexbox, positioning, the cascade and specificity, units and sizing, display and visibility, grid, pseudo-classes and elements, transitions and animations, responsive design, and custom properties. You now have what you need to take a plain HTML page and make it look and behave like a real, polished site. From here, the natural next step is bringing pages to life with logic — continue to the JavaScript Course.