CSS Animations

CSS animations allow you to create smooth transitions and effects on web elements without relying on JavaScript. These animations involve defining keyframes for stages of the animation and applying properties to control its behavior.

Components of CSS Animation

1. Keyframes: Define the animation’s start, end, and intermediate steps.


@keyframes animation-name {
  0% { property: value; }
  50% { property: value; }
  100% { property: value; }
}

2. Animation Properties:

Apply to elements to control the animation’s behavior.

Property
Description
Example Value
animation-name
Specifies the keyframes to use
move
animation-duration
Sets how long the animation lasts.
2s, 500ms
animation-timing-function
Specifies the speed curve.
linear, ease
animation-delay
Delays the start of the animation.
1s
animation-iteration-count
Number of times the animation repeats.
1, infinite
animation-direction
Specifies if the animation reverses.
normal, alternate
animation-fill-mode
Applies styles before/after the animation.
forwards, backwards
animation
Combines all animation properties.
move 2s ease 1

Animation Properties

Example 1: Bouncing Box

HTML:


<div class="box"></div>

CSS:


.box {
  width: 100px;
  height: 100px;
  background-color: red;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }   /* Start and end at the original position */
  50% { transform: translateY(-50px); }   /* Move up */
}

Effect: The box moves up and down repeatedly.

Example 2: Fading Text

HTML:


<p class="fade-text">Hello World!</p>

CSS:


.fade-text {
  font-size: 24px;
  color: black;
  animation: fade 3s infinite;
}

@keyframes fade {
  0% { opacity: 1; }  /* Fully visible */
  50% { opacity: 0.5; } /* Semi-transparent */
  100% { opacity: 1; } /* Fully visible again */
}

Effect: The text fades in and out.

Example 3: Color Changing Button

HTML:


<button class="color-button">Click Me</button>

CSS


.color-button {
  padding: 10px 20px;
  font-size: 18px;
  border: none;
  cursor: pointer;
  animation: color-change 4s infinite alternate;
}

@keyframes color-change {
  0% { background-color: lightblue; }
  100% { background-color: lightcoral; }
}

Effect: The button smoothly transitions between light blue and light coral.