Chapitre 9 : Transitions, animations et effets

Maîtrisez les animations CSS pour créer des interfaces dynamiques et engageantes.

1. Les transitions CSS

Les transitions permettent d'animer le changement d'une propriété CSS sur une durée définie.

1.1 Syntaxe de base

element {
  transition: propriété durée timing-fonction délai;
}

Exemple :

button {
  background-color: #00897b;
  transition: background-color 0.5s ease-in-out;
}

button:hover {
  background-color: #004d40;
}

2. Propriétés animables

Voici quelques propriétés couramment animées avec des transitions :

  • color, background-color
  • width, height
  • transform (rotation, échelle, etc.)
  • opacity

3. Les animations CSS

Les animations permettent de créer des effets complexes à l'aide de keyframes.

3.1 Syntaxe

@keyframes nomAnimation {
  from { ... }
  to { ... }
}

Ou :

@keyframes nom {
  0% { ... }
  50% { ... }
  100% { ... }
}

3.2 Exemple de base

@keyframes slide {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(200px);
  }
}

.box {
  animation: slide 2s ease-in-out;
}

4. Propriétés de l'animation

  • animation-name
  • animation-duration
  • animation-timing-function
  • animation-delay
  • animation-iteration-count (ex : infinite)
  • animation-direction (normal, reverse, alternate)
  • animation-fill-mode (forwards, backwards)

Exemple complet :

.box {
  animation: slide 3s ease-out 1s infinite alternate;
}

5. Animation avec transform et opacity

@keyframes fadeZoom {
  0% {
    opacity: 0;
    transform: scale(0.8);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.element {
  animation: fadeZoom 0.8s ease forwards;
}

6. Bonnes pratiques

  • Utiliser transform et opacity (performants)
  • Limiter les animations trop longues ou fréquentes
  • Ajouter un :prefers-reduced-motion pour l'accessibilité

7. À éviter

  • Changer directement top, left (moins performant)
  • Animer le width/height de gros éléments sans nécessité
  • Abuser des animations : elles doivent améliorer l'UX, pas la distraire

8. Exercice pratique

Objectif : Créer un bouton qui change de taille et de couleur au survol, et une boîte qui rebondit continuellement.

HTML :

<button class="btn">Survolez-moi</button>
<div class="boite"></div>

CSS :

.btn {
  background-color: #00796b;
  color: white;
  padding: 1em 2em;
  transition: background-color 0.3s ease, transform 0.3s ease;
}

.btn:hover {
  background-color: #004d40;
  transform: scale(1.1);
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-30px); }
}

.boite {
  width: 50px;
  height: 50px;
  background: #26a69a;
  animation: bounce 1s ease-in-out infinite;
  margin-top: 2em;
}

9. À retenir

  • transition permet d'adoucir les changements
  • @keyframes permet de créer des animations complexes
  • Favoriser les effets discrets et performants (via transform et opacity)