CSS transitions allow you to animate changes to CSS properties smoothly over time. Instead of a property changing instantly, transitions make it happen gradually.
They are very useful for hover effects, interactive buttons, menus, and modern UI design.
1️⃣ What is a Transition?
A transition is like a “bridge” between two states of an element:
Example:
Changing a box color from blue to green on hover smoothly.
2️⃣ Transition Properties
The main CSS properties used for transitions:
3️⃣ Basic Transition Example
.box {
width: 100px;
height: 100px;
background-color: blue;
transition-property: background-color;
transition-duration: 1s;
}
.box:hover {
background-color: green;
}
Explanation:
background-color: bluebackground-color: green4️⃣ Transition Shorthand Property
Instead of writing multiple lines, you can use the shorthand transition property:
transition: property duration timing-function delay;
Example:
.box {
transition: background-color 1s ease-in-out 0s;
}
This does the same as the previous example in one line.
5️⃣ Multiple Transitions
You can transition more than one property at the same time using commas:
.box {
transition: width 1s ease, height 1s ease, background-color 0.5s linear;
}
.box:hover {
width: 150px;
height: 150px;
background-color: orange;
}
This animates width, height, and background color simultaneously with different timing.
6️⃣ Smooth Button Hover
<button class="btn">Hover Me</button>
.btn {
padding: 10px 20px;
background-color: teal;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.5s ease, transform 0.3s ease;
}
.btn:hover {
background-color: darkcyan;
transform: scale(1.1); /* Makes the button slightly larger */
}
Explanation:
scale(1.1))transition7️⃣ Important Notes
width, height, color, background-color, opacity, transform):hover, :focus) or JavaScript can trigger transitionstransition to save lines of code<!DOCTYPE html>
<html>
<head>
<title>CSS Transitions Example</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
margin: 50px;
transition: background-color 1s ease, transform 0.5s ease;
}
.box:hover {
background-color: orange;
transform: rotate(20deg) scale(1.2);
}
.btn {
padding: 10px 20px;
background-color: teal;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.5s ease, transform 0.3s ease;
margin: 20px;
}
.btn:hover {
background-color: darkcyan;
transform: scale(1.1);
}
</style>
</head>
<body>
<div class="box"></div>
<button class="btn">Hover Me</button>
</body>
</html>