CSSCSS · Lesson 7 of 9

Animations & Transitions

CSS can animate almost any property. Done well, animations guide attention and provide feedback. Done poorly, they make users want to leave your site.

CSS
/* Transitions — animate between two states */
.button {
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  /* transition: property duration timing-function delay */
  transition: background-color 0.2s ease, transform 0.1s ease;
}

.button:hover {
  background-color: #0056b3;
  transform: translateY(-2px);  /* lift up slightly */
}

.button:active {
  transform: translateY(0);     /* push back down */
}

/* Transition multiple properties */
.card {
  transition: all 0.3s ease;   /* 'all' — convenient but use sparingly */
}

.card:hover {
  transform: scale(1.03);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}
CSS
/* Keyframe animations — for complex, multi-step animations */
@keyframes fadeIn {
  from { opacity: 0; }
  to   { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(30px); opacity: 0; }
  to   { transform: translateY(0);    opacity: 1; }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50%       { transform: scale(1.05); }
}

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

/* Apply animations */
.fade-in {
  animation: fadeIn 0.5s ease;
}

.slide-up {
  animation: slideUp 0.6s ease backwards;  /* backwards: apply from-state before start */
}

/* Staggered animations */
.list-item:nth-child(1) { animation: slideUp 0.4s 0.0s ease backwards; }
.list-item:nth-child(2) { animation: slideUp 0.4s 0.1s ease backwards; }
.list-item:nth-child(3) { animation: slideUp 0.4s 0.2s ease backwards; }

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #ddd;
  border-top-color: #007bff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

/* Respect user preference for reduced motion */
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}
⚠ Warning
Always include a prefers-reduced-motion media query. Some users have vestibular disorders that make motion literally nauseating. It's two lines of CSS and it's the right thing to do.