In modern web design, motion is a key element for creating engaging user experiences. CSS provides two powerful tools for this: transitions and animations.
CSS Transitions
Transitions allow you to change property values smoothly over a given duration. Instead of a property change being instant, you can make it happen gradually. Think of a button changing color on hover.
The magic happens with the transition property. It's a shorthand for four sub-properties:
- transition-property: The CSS property to transition (e.g., background-color, opacity).
- transition-duration: How long the transition takes (e.g., 0.3s, 300ms).
- transition-timing-function: The speed curve of the transition (e.g., ease-in, linear, cubic-bezier(...)). This controls the acceleration and deceleration.
- transition-delay: The time to wait before starting the transition.
Code Snippet: A Simple Button Transition Let's make a button that smoothly fades to a new color when you hover over it.
HTML:
HTML
<button class="transition-btn">Hover Me</button>
CSS:
CSS
.transition-btn {
  background-color: #3498db;
  color: white;
  padding: 15px 25px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  /* Shorthand transition for background-color over 0.4 seconds with an 'ease' curve */
  transition: background-color 0.4s ease;
}
.transition-btn:hover {
  background-color: #2980b9;
}
CSS Animations with @keyframes
For more complex, multi-step animations, you need keyframes. Animations are defined with the @keyframes rule and then applied to an element using the animation property.
First, you define the animation's "story" with @keyframes. You give it a name and define what happens at different points in time (from 0% to 100%).
Code Snippet: A Pulsing Dot Animation Let's create a simple pulsing dot effect.
HTML:
HTML
<div class="pulsing-dot"></div>
CSS:
CSS
/* 1. Define the keyframes */
@keyframes pulse-animation {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.5;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
/* 2. Apply the animation to an element */
.pulsing-dot {
  width: 20px;
  height: 20px;
  background-color: #e74c3c;
  border-radius: 50%;
  
  /* Apply the animation */
  animation-name: pulse-animation;
  animation-duration: 2s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite; /* Make it loop forever! */
}
The animation property is also a shorthand for properties like animation-name, animation-duration, animation-timing-function, and animation-iteration-count.