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.
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.
selector {
transition: property duration timing-function delay;
}
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
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)
Determines the acceleration and deceleration of the transition. It controls the pacing of the transition and can be one of several predefined 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
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)
<!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>