Skills101

AdvancedWeb Development · Lesson 19 of 19 · Updated ·

CSS Variables, Transitions, Transforms and Animations — With Dark Mode

Two features make modern CSS much nicer to work with. Custom properties (CSS variables) let you define a colour or size once and reuse it everywhere — the basis of themes and dark mode. Transitions and animations add small, smooth movements that make an interface feel responsive. This lesson covers both, plus the performance and accessibility rules that separate good motion from annoying motion.

1. CSS custom properties (variables)

A custom property is a name starting with two dashes. You set it once and read it with var():

:root {
  --brand: #c94f0f;
  --text: #1f2937;
  --bg: #ffffff;
  --radius: 12px;
  --space: 16px;
}

.button {
  background: var(--brand);
  color: white;
  border-radius: var(--radius);
  padding: calc(var(--space) / 2) var(--space);
}

.card {
  background: var(--bg);
  color: var(--text);
  border-radius: var(--radius);
  padding: var(--space);
}
  • :root is the <html> element, so variables defined there are available everywhere.
  • Change --brand in one place and every button, link and border using it updates.
  • var(--accent, orange) gives a fallback if --accent is not defined.
  • calc() can do maths with variables: calc(var(--space) * 2).

They cascade and inherit

Unlike Sass variables (which are replaced when the CSS is compiled), CSS custom properties are live in the browser. They follow the normal cascade, so you can override them for one part of the page:

.danger-zone { --brand: #dc2626; }   /* buttons inside this section turn red */

And JavaScript can change them at run time:

// Browser only
document.documentElement.style.setProperty("--brand", "#2563eb");

2. Building a dark mode

The same card in light and dark themes: only the values of --bg, --text and --muted change, while the component CSS stays the same

The trick: components only use variables, and themes only change the values.

:root {
  --bg: #ffffff;
  --text: #1f2937;
  --muted: #6b7280;
}

/* Follow the operating-system setting */
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #111827;
    --text: #f9fafb;
    --muted: #9ca3af;
  }
}

/* Or let the user choose with a button that sets <html data-theme="dark"> */
:root[data-theme="dark"] {
  --bg: #111827;
  --text: #f9fafb;
  --muted: #9ca3af;
}

body { background: var(--bg); color: var(--text); }
// Browser only: a theme toggle button that remembers the choice
const btn = document.querySelector("#theme-toggle");
btn.addEventListener("click", () => {
  const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
  document.documentElement.dataset.theme = next;
  localStorage.setItem("theme", next);
});

Check text contrast in both themes; light grey text on a dark grey background is a common accessibility failure.

3. Transitions: smooth changes between two states

A transition animates a property when its value changes — for example on :hover or when JavaScript adds a class.

.button {
  background: var(--brand);
  transform: translateY(0);
  transition: background-color 200ms ease, transform 200ms ease;
}

.button:hover {
  background: #a93f08;
  transform: translateY(-2px);
}

The transition shorthand is: property, duration, timing function, optional delay.

PartExampleMeaning
propertytransform, opacity, allwhat to animate (all is easy but can animate things you did not intend)
duration200ms, 0.3show long
timing functionease, linear, ease-in, ease-outthe speed curve
delay100mswait before starting

Timing functions (easing)

Speed curves of the CSS timing functions: linear is a straight line; ease-in starts slowly; ease-out starts fast and slows down at the end; ease starts quickly and settles gently

  • ease-out feels natural for things entering (a menu sliding in): fast start, gentle stop.
  • ease-in suits things leaving.
  • linear suits continuous motion such as a spinner.
  • cubic-bezier(…) lets you design your own curve.

Durations: most interface transitions feel right between about 150 ms and 300 ms. Longer ones start to feel slow.

4. Transforms: move, scale and rotate

transform changes how an element is drawn without changing the layout around it:

FunctionExampleEffect
translate(x, y)translateY(-2px)move
scale(n)scale(1.05)grow or shrink
rotate(angle)rotate(45deg)rotate
combinedtranslateX(10px) rotate(5deg)applied in order

transform-origin sets the point it scales or rotates around (centre by default).

Because transforms do not move other elements, they are perfect for hover effects: a card can lift (translateY(-4px)) without pushing its neighbours.

5. Keyframe animations

Transitions go from A to B when something changes. Animations can have many steps, run on their own, and repeat.

@keyframes pulse {
  0%   { transform: scale(1);    opacity: 1; }
  50%  { transform: scale(1.15); opacity: 0.7; }
  100% { transform: scale(1);    opacity: 1; }
}

.live-badge {
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.spinner {
  width: 32px;
  height: 32px;
  border: 4px solid #e5e7eb;
  border-top-color: var(--brand);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}
animation partExample
namepulse
duration1.5s
timing functionease-in-out
iteration count3, infinite
directionnormal, alternate (forwards, then backwards)
fill modeforwards keeps the final state after it ends

The pulsing "LIVE" badge for a live class and the loading spinner above are two of the most common real uses.

6. Performance: animate the cheap properties

When a property changes, the browser may have to redo layout (work out sizes and positions), then paint (draw pixels), then composite (put layers together).

Property typeExamplesCost
layoutwidth, height, top, left, marginhighest: everything around may move
paintcolor, background-color, box-shadowmedium
composite onlytransform, opacitylowest: often handled by the GPU

So animate transform: translateX() instead of left, and transform: scale() instead of width. On budget phones, this is the difference between smooth motion and stutter.

7. Respect reduced motion

Some people get dizzy or nauseous from movement on screen. Operating systems have a "reduce motion" setting, and CSS can read it:

@media (prefers-reduced-motion: reduce) {
  *,
  *::before,
  *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

This is one of the rare places where !important is reasonable: it is a user preference that should win. Also avoid anything that flashes more than three times per second.

Common mistakes

  • Forgetting the two dashes (var(brand) instead of var(--brand)).
  • Hard-coding colours in components, which makes dark mode a rewrite.
  • transition: all 1s everywhere: slow, and it animates unexpected properties.
  • Animating width, top or left instead of transform.
  • Endless decorative animations that distract from the content, and ignoring prefers-reduced-motion.

Quick recap

  • --name: value defines a custom property; var(--name, fallback) reads it; they cascade and can change at run time.
  • Dark mode = same components, different variable values (prefers-color-scheme or a data-theme toggle).
  • transition: property duration easing animates between two states; keep it around 150–300 ms.
  • transform (translate, scale, rotate) moves things without affecting layout.
  • @keyframes + animation for multi-step or repeating motion.
  • Animate transform and opacity; respect prefers-reduced-motion.

Practice what you learned

📝 Quiz: CSS Variables and Animations5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →