CSS variables and transitions
Custom properties (CSS variables)
When the same colour appears in twenty places, changing it means twenty edits, and you will miss one. Custom properties give a value a name:
:root {
--brand: #ab2023;
--space: 16px;
}
.header { background-color: var(--brand); }
.card { padding: var(--space); border-color: var(--brand); }
- Names start with two dashes:
--brand. :rootis the whole document, so properties defined there are available everywhere.var(--brand)reads the value.var(--accent, gold)usesgoldif--accentis not set.
Change --brand once and the whole site follows. Unlike older CSS tools, custom properties can even be changed per section or by JavaScript at runtime, which is how dark modes are usually built.
Hover states and transitions
:hover styles an element while the mouse is over it (and :focus-visible when it is reached with the keyboard: always style both for buttons).
By default the change is instant. A transition animates it:
.button {
background-color: var(--brand);
transition: background-color 0.3s;
}
.button:hover,
.button:focus-visible {
background-color: var(--brand-dark);
}
transition takes the property to animate and how long it takes. Keep interface transitions short (0.15s to 0.3s): long enough to feel smooth, short enough not to feel slow.
Your task
- On
:root, define--brand: #ab2023and--brand-dark: #6f1416. - Give
.buttonthe backgroundvar(--brand), and atransitiononbackground-colorlasting0.3s. - Add a
.button:hoverrule that usesvar(--brand-dark).