HTML & CSS Course
HTML & CSS
/
Intermediate

CSS Variables

Definition

Custom properties (`--name`) defined by CSS authors that contain specific values to be reused throughout a document.

Explain Like I'm New

Imagine you use a specific shade of blue (`#3b82f6`) 50 times in your CSS file for buttons, borders, and text. Then the boss says 'Change the blue to green'. You have to find and replace all 50 lines manually. With CSS Variables, you define `--primary-color: #3b82f6` at the top of the file, and use `var(--primary-color)` 50 times. To change the theme, you only edit one line of code!

Real World Example

Implementing Dark Mode! You swap out the `--bg-color` variable from 'white' to 'black' using a tiny bit of JavaScript, and the entire website instantly updates.

Common Use Cases

  • •Theming / Dark Mode
  • •Maintaining large CSS codebases

Interactive Example

Interview Questions

basic

  • Where do you usually define global CSS variables so they can be accessed anywhere?

intermediate

  • What function is used to apply a variable to a property?

Flash Cards

Question

Where to define?

Click to reveal answer
Answer

In the `:root` pseudo-class (which represents the `<html>` element). Example: `:root { --main-color: red; }`.

Question

What function?

Click to reveal answer
Answer

The `var()` function. Example: `color: var(--main-color);`.