Web Development · Module 4 · Lesson 41 min read

CSS Variables, Transitions & Animations

CSS custom properties (variables)

Define once, reuse everywhere, and change them for themes:

CSS
:root {
  --brand: #6366f1;
  --radius: 12px;
}
.button { background: var(--brand); border-radius: var(--radius); }

[data-theme="dark"] { --brand: #818cf8; }

Unlike Sass variables, CSS variables are live: JavaScript can change them at runtime with element.style.setProperty('--brand', 'red').

Transitions: smooth changes between states

CSS
.button { transition: transform 0.2s ease, background 0.2s ease; }
.button:hover { transform: translateY(-2px); }

Animations: keyframes

CSS
@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50%      { transform: scale(1.08); }
}
.badge { animation: pulse 1.5s ease-in-out infinite; }

Performance tips

  • Animate transform and opacity only; they don't trigger layout, so they stay smooth at 60 fps.
  • Avoid animating width, height, top or margin.
  • Respect users who get motion sickness:
CSS
@media (prefers-reduced-motion: reduce) {
  * { animation: none !important; transition: none !important; }
}

Example

HTML
<style>
  :root { --brand: #6366f1; --radius: 12px; }
  body { font-family: sans-serif; padding: 24px; }
  .btn {
    background: var(--brand); color: white; border: 0;
    padding: 12px 20px; border-radius: var(--radius);
    font-size: 16px; cursor: pointer;
    transition: transform .2s ease, box-shadow .2s ease;
  }
  .btn:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgb(99 102 241 / 40%); }
  @keyframes pulse { 50% { transform: scale(1.1); } }
  .dot {
    display: inline-block; width: 14px; height: 14px; margin-left: 12px;
    border-radius: 50%; background: #22c55e;
    animation: pulse 1.2s ease-in-out infinite;
  }
  @media (prefers-reduced-motion: reduce) { .dot { animation: none; } }
</style>

<button class="btn"
  onclick="document.documentElement.style.setProperty('--brand', '#ef4444')">
  Hover me / click to change theme
</button>
<span class="dot"></span>