Var() function
Learn to use variables with var().
The var() function
To use a variable you defined, call the var() function. Write the variable name inside it; the value is placed there automatically. This is the step that makes a variable actually useful.
Example: color: var(--color); or padding: var(--space);. Don't quote the variable name; write it directly. So the definition lives in one place, the use in dozens.
var() in many properties
var() is not just for colors; it works in any CSS property. Use it for lengths, percentages, colors, shadows, even as part of a value.
Examples: padding: var(--space) var(--space-xl);, border: 1px solid var(--border), box-shadow: 0 4px var(--shadow). You can bind part of a value to a variable; that's where the flexibility comes from.
Exercise Use var() in a button
Inside a .cta selector, write three properties: color: var(--text);, background: var(--brand);, padding: var(--gap);.
Show example solution
open a .cta selector and use var() in three properties.
Example solution:
.cta {
color: var(--text);
background: var(--brand);
padding: var(--gap);
}
Test yourself
-
Which uses a variable correctly with var()?
- var: --color
- var(--color)
- --color()
- call(--color)
Show answer
var(--color) — Correct! You write the variable name inside var().
-
Call the variable in the color property
a { color: ____; }Show answer
a { color: var(--color); } -
Match the usages
- color: var(--color)
- text color
- padding: var(--space)
- padding
- background: var(--bg)
- background
- border: 1px solid var(--border)
- border