Lesson 14 of 14 · 12 min

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.
  • :root is the whole document, so properties defined there are available everywhere.
  • var(--brand) reads the value. var(--accent, gold) uses gold if --accent is 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

  1. On :root, define --brand: #ab2023 and --brand-dark: #6f1416.
  2. Give .button the background var(--brand), and a transition on background-color lasting 0.3s.
  3. Add a .button:hover rule that uses var(--brand-dark).
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Buttons</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <a href="#" class="button">Start learning</a>
</body>
</html>

Your page

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…