CSS Transition

CSS transitions provide a way to animate changes to CSS properties, creating smooth and gradual effects rather than abrupt jumps. This feature enhances user experience by adding visual feedback and making interactions more engaging.

Transitions allow you to define how a property changes over time, offering control over the timing, speed, and easing of the animation. Instead of using JavaScript or other complex methods to achieve animations, CSS transitions offer a simpler and more performant approach.

What is CSS Transition?

A CSS transition enables you to change the value of a CSS property gradually from its initial state to a new state over a specified duration. This smooth transition effect occurs when a property value changes due to user interaction or other events.

For example, if you want a button to change its background color when hovered over, you can use CSS transitions to animate the color change, making it smooth and visually appealing.

Syntex:

selector {
transition: property duration timing-function delay;
}

Components of CSS Transitions

1. Property:

Specifies which CSS property will be animated. This can be any animatable property such as color, width, height, opacity, transform, etc.

Example: background-color, width

2. Duration:

Defines the length of time the transition should take from start to finish. This is specified in seconds (s) or milliseconds (ms).

Example: 0.5s (500 milliseconds), 2s (2 seconds)

3. Timing Function:

Determines the acceleration and deceleration of the transition. It controls the pacing of the transition and can be one of several predefined values.

Common Values:

linear: Constant speed from start to end

ease: Slow at the beginning, faster in the middle, and slow at the end

ease-in: Starts slowly and speeds up

ease-out: Starts quickly and slows down

ease-in-out: Starts and ends slowly, with faster movement in the middle

4. Delay:

Specifies a delay before the transition begins, allowing the transition to start after a certain amount of time. This is also specified in seconds (s) or milliseconds (ms).

Example: 0.2s (200 milliseconds), 1s (1 second)

Example:

<!DOCTYPE html>
<html>
<head>

  <title>CSS Transition Example</title>

  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      transition: background-color 0.5s ease-in-out, width 1s ease-in-out;
    }

    .box:hover {
      background-color: lightgreen;
      width: 200px;
    }
  </style>

</head>

<body>

  <div class="box">Move your cursor here.</div>

</body>
</html>