CSS transitions allow you to animate changes in CSS properties smoothly over a period of time, rather than happening instantly.
1. Basic Syntax of CSS Transitions
To create a transition, use the transition property.
.element {
transition: property duration timing-function delay;
}
2. Example: Changing Background Color
When hovering over the element, the background color **gradually** changes.
.button {
background-color: blue;
color: white;
padding: 10px 20px;
transition: background-color 0.5s ease-in-out;
}
.button:hover {
background-color: red;
}
3. Transition Multiple Properties
You can transition multiple CSS properties at once.
.box {
width: 100px;
height: 100px;
background-color: green;
transition: width 0.5s, height 0.5s, background-color 0.5s;
}
.box:hover {
width: 150px;
height: 150px;
background-color: yellow;
}
4. Using Different timing-functions
The timing-function defines the speed of the transition.
.box {
transition: all 1s ease-in-out;
}
linear: Constant speedease: Starts slow, speeds up, then slows downease-in: Starts slow, then speeds upease-out: Starts fast, then slows downease-in-out: Slow start and end
5. Adding Delay to Transitions
You can **delay** a transition using the **fourth** value in the transition property.
.box {
transition: background-color 1s ease-in 0.5s;
}
6. Transform with Transitions
Apply **scale, rotate, and translate** effects smoothly.
.box {
transition: transform 0.5s ease-in-out;
}
.box:hover {
transform: scale(1.2) rotate(10deg);
}
7. Chaining Transitions
You can combine multiple transitions for complex effects.
.box {
transition: background-color 0.5s, transform 0.5s;
}
.box:hover {
background-color: purple;
transform: translateX(50px);
}
Conclusion
CSS transitions enhance user experience by creating smooth animations. Experiment with different properties, durations, and timing functions to create stunning effects!