Learn CSS from Scratch

Transitions, Animations and CSS Variables

Lesson 9 of 9 2 min read Updated 10 October 2026

Transitions

A transition smoothly changes a property over time.

<style>
.btn { padding: 10px 22px; border: 0; border-radius: 10px; background: #2563eb; color: #fff; cursor: pointer; transition: transform .2s ease, box-shadow .2s ease, background .2s; }
.btn:hover { transform: translateY(-3px); box-shadow: 0 10px 20px rgba(37,99,235,.35); background: #1d4ed8; }
</style>
<button class="btn">Hover me</button>

Syntax: transition: property duration timing-function delay;

Transforms

transform: translateX(20px) rotate(10deg) scale(1.1);

Keyframe animations

<style>
@keyframes bounce { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-20px); } }
.ball { width: 40px; height: 40px; border-radius: 50%; background: #7c3aed; animation: bounce 1s ease-in-out infinite; margin: 30px; }
</style>
<div class="ball"></div>

CSS variables (custom properties)

Variables store values you reuse. This is how themes and dark modes are built.

<style>
:root { --brand: #2563eb; --radius: 12px; }
.card { border: 2px solid var(--brand); border-radius: var(--radius); padding: 16px; }
.card h3 { color: var(--brand); margin: 0 0 8px; }
</style>
<div class="card"><h3>Themed card</h3><p>Change --brand once and everything updates.</p></div>

Animation good practice

  • Animate transform and opacity for smooth performance.
  • Keep animations short and meaningful.
  • Respect users who prefer less motion:
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }

Practice

Create a card that lifts on hover, uses CSS variables for its colours and fades in when the page loads.

Next steps

Continue to the JavaScript course to make your pages interactive.

Practice tasks

Reading is not enough. Try these without copying code, then compare with the lesson.

  • Add a hover transition to a button.
  • Create a keyframe animation that fades in a card.
  • Define colours as CSS variables and change the theme from one place.

Common mistakes

  • Animating properties that cause layout recalculation.
  • Ignoring users who prefer reduced motion.

Quick check

How do you declare a CSS variable?

With two dashes, like –brand, and use it with var(–brand).

What does transition do?

It animates the change of a property over time.