CSS Transitions
Introduction
CSS transitions allow you to create smooth, gradual changes in CSS properties over a specified duration. They provide a way to animate elements without using JavaScript, making them incredibly efficient and easy to implement.
Do You Know?
Transitions can be applied to almost any CSS property, including background color, font size, width, height, opacity, and more.
Hover Effects
Hover effects are a classic example of using transitions. By adding a transition to a property like background color, you can create a smooth animation when the mouse hovers over an element.
.button {
background-color: blue;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: red;
}
Important Note!
Always define the initial state (the default) and the hover state (the changed state) for your transition effect.
Transition Property
The transition-property
property defines which CSS property you want to animate. It can accept one or multiple property names, separated by commas.
transition-property: background-color, color, width;
Transition Delay
The transition-delay
property specifies the amount of time to wait before the transition starts. It is measured in seconds (s) or milliseconds (ms).
transition-delay: 1s; /* Wait 1 second before starting the transition */
Transition Timing Function
The transition-timing-function
property determines the speed curve of the transition. Common options include:
linear
: Constant speed throughout the transition.ease
: Default value, smooth start and end.ease-in
: Starts slowly, speeds up.ease-out
: Starts quickly, slows down.ease-in-out
: Starts slowly, speeds up, then slows down.
transition-timing-function: ease-in-out;
Transition Duration
The transition-duration
property defines the length of time the transition takes to complete. It is measured in seconds (s) or milliseconds (ms).
transition-duration: 0.5s; /* Transition takes 0.5 seconds */
Avoid This!
Don't overuse transitions or create transitions that are too long or too short. They should be subtle and enhance the user experience, not distract from it.
Summary
- CSS transitions enable smooth animations of CSS properties over time.
- Transitions are defined using the
transition
shorthand property or individual properties liketransition-property
,transition-duration
,transition-delay
, andtransition-timing-function
. - Hover effects are a common use case for transitions.
- Transitions can significantly enhance user experience and make your web pages more engaging.