CSS Transitions

CSS transitions allow you to change property values smoothly over a specific duration. Instead of changing styles instantly, transitions create animation effects that improve user experience and make websites feel interactive.

What are CSS Transitions

A CSS transition controls the change between two states of an element. For example, when a user hovers over a button, the color can change gradually instead of instantly.

Why use CSS Transitions

CSS transitions improve visual appeal and user engagement. They help guide user attention and make interactions smoother. Transitions are lightweight and do not require JavaScript for basic animations.

Basic Syntax

A transition is defined using the transition property. It includes the property you want to animate, the duration, and optional timing and delay values.

Example

button
{
background color blue
transition background color 0.5s ease
}

button hover
{
background color green
}

In this example, the button changes color smoothly when hovered.

Transition Properties

Transition property defines which CSS property will change. You can target specific properties like color, width, height, or use all to apply transitions to everything.

Transition duration defines how long the transition takes. It can be in seconds or milliseconds.

Transition timing function controls the speed curve of the animation. Common values include ease linear ease in ease out and ease in out.

Transition delay sets a waiting time before the transition starts.

Example with multiple properties

div
{
width 100px
height 100px
background color red
transition width 1s ease height 1s ease
}

div hover
{
width 200px
height 200px
}

Shorthand Property

You can combine all transition properties into one line using shorthand.

Example

div
{
transition all 0.3s ease in out 0.1s
}

Common Use Cases

Buttons with hover effects
Navigation menus
Image zoom effects
Cards and UI components
Form input highlights

Best Practices

Use transitions only when needed to avoid slowing down the website.
Keep durations short for better user experience.
Avoid animating heavy properties like width and height too often.
Use ease in out for natural motion.

Practice Exercise

Create a button that changes background color and size smoothly when hovered. Try different timing functions and durations to see how the animation changes.

Conclusion

CSS transitions are a simple yet powerful way to enhance your website design. By using them effectively, you can create smooth and engaging user interactions without complex code.