CSS Transitions and Animations

1. Introduction to CSS Transitions

CSS Transitions allow you to smoothly change property values over a specified duration. They are ideal for creating simple animations, such as hover effects or state changes.

Key properties for transitions:


2. Using CSS Transitions

To create a transition, specify the property you want to animate and the duration of the transition.

.box {
  width: 100px;
  height: 100px;
  background-color: #2260e6;
  transition: width 2s; /* Transition the width property over 2 seconds */
}

.box:hover {
  width: 200px; /* New width on hover */
}

You can also transition multiple properties at once:

.box {
  transition: width 2s, height 2s, background-color 2s; /* Transition multiple properties */
}

3. Transition Timing Functions

The transition-timing-function property controls the speed curve of the transition. Common values include:

.box {
  transition-timing-function: ease-in-out; /* Slow start and end */
}

4. Introduction to CSS Animations

CSS Animations allow you to create more complex and dynamic animations using @keyframes. Unlike transitions, animations can loop, alternate, and have multiple steps.

Key properties for animations:


5. Using @keyframes

The @keyframes rule defines the steps of an animation. You can specify styles at different points in the animation timeline.

@keyframes slide {
  0% {
    transform: translateX(0);
  }
  50% {
    transform: translateX(100px);
  }
  100% {
    transform: translateX(0);
  }
}

.box {
  animation: slide 3s infinite; /* Apply the slide animation */
}

6. Animation Properties

You can control the behavior of animations using properties like animation-iteration-count, animation-direction, and animation-fill-mode.

.box {
  animation-name: slide;
  animation-duration: 3s;
  animation-iteration-count: infinite; /* Repeat infinitely */
  animation-direction: alternate; /* Alternate direction */
  animation-fill-mode: forwards; /* Retain the final state */
}

7. Combining Transitions and Animations

You can combine transitions and animations to create more dynamic effects. For example, use a transition for hover effects and an animation for continuous motion.

.box {
  width: 100px;
  height: 100px;
  background-color: #2260e6;
  transition: background-color 0.5s ease; /* Transition for hover */
  animation: slide 3s infinite; /* Animation for continuous motion */
}

.box:hover {
  background-color: #ff0000; /* Change color on hover */
}