Skip to main content

What are CSS variables? How do you declare a variable in CSS?

CSS variables (or custom properties) are custom values that can be declared once and reused across styles. They help avoid duplicating the same numbers and colors, and speed up maintaining and changing a design.


How to declare a variable

Variables are declared inside a selector and start with --.

They are usually placed in :root so they are available everywhere:

css
:root { --main-color: #3498db; --font-size: 18px; }

How to use a variable

To apply it, the var() function is used:

css
p { color: var(--main-color); font-size: var(--font-size); }

What's important to know

  • a variable's scope equals the scope of the selector where it is declared;
  • variables can be overridden at any level;
  • unlike preprocessors (Sass/LESS), CSS variables work dynamically, they can be changed even from JavaScript or based on state (for example, for a dark theme).

Summary: CSS variables let you store repeating values (for example, colors, sizes) in one place and reuse them, by declaring them with --name and applying them via var().

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.