CSS Transitions
CSS Transitions allow you to smoothly change property values over a specified duration. They enhance user experience by creating visually appealing animations when properties change.
Key Topics
Basic Transition
A basic transition changes a single property smoothly over time when triggered by an event such as a hover.
<style>
.basic-transition {
width: 100px;
height: 100px;
background-color: #007BFF;
transition: background-color 0.5s ease;
}
.basic-transition:hover {
background-color: #FF5733;
}
</style>
<div class="basic-transition"></div>
Explanation: When the element is hovered over, the background color transitions smoothly from blue to orange over 0.5 seconds.
Transition Duration
The transition-duration
property specifies the length of time a transition should take.
<style>
.duration-transition {
width: 100px;
height: 100px;
background-color: #007BFF;
transition: background-color 2s;
}
.duration-transition:hover {
background-color: #FF5733;
}
</style>
<div class="duration-transition"></div>
Explanation: The transition takes 2 seconds to complete, making the color change more gradual.
Timing Function
The transition-timing-function
property defines how the transition progresses over time. Common values include ease
, linear
, ease-in
, ease-out
, and ease-in-out
.
<style>
.timing-function {
width: 100px;
height: 100px;
background-color: #007BFF;
transition: background-color 1s ease-in-out;
}
.timing-function:hover {
background-color: #FF5733;
}
</style>
<div class="timing-function"></div>
Explanation: The ease-in-out
timing function creates a smooth start and end for the transition.
Multiple Properties
You can apply transitions to multiple properties by separating them with commas.
<style>
.multiple-properties {
width: 100px;
height: 100px;
background-color: #007BFF;
transform: scale(1);
transition: background-color 0.5s ease, transform 0.5s ease;
}
.multiple-properties:hover {
background-color: #FF5733;
transform: scale(1.5);
}
</style>
<div class="multiple-properties"></div>
Explanation: Both the background color and the size of the element change smoothly when hovered over, creating a combined effect.
Key Takeaways
- Transitions: Allow properties to change smoothly over time.
- Duration: Use
transition-duration
to control how long the transition lasts. - Timing Functions: Define how the transition progresses using values like
ease
andlinear
. - Multiple Properties: Apply transitions to multiple properties for complex effects.
- Events: Transitions are triggered by events such as hover or focus.