Transitions
Transition in CSS is used to change values over a specified duration, animating the property changes, rather than having them occur immediately.
Examples
- Adding transition on click using JS
.box {
width: 2rem;
transition: width 2s ease;
}
const box = document.querySelector(".box");
box.onclick = (_event) => {
box.style.width = "10rem";
};
In this case, the box element width will be increased when the box is clicked.
Don't forget to reset width to the original value.
- For changing the color on hover,
.box {
-webkit-transition: background-color 2s ease-out;
-moz-transition: background-color 2s ease-out;
-o-transition: background-color 2s ease-out;
transition: background-color 2s ease-out;
}
.box:hover {
background-color: green;
}
In this example the color of the box will be changed gradually over the period of 2 second.
The webkit, moz and o transition is needed for cross platform working.