CSS transitions are a powerful tool for creating smooth animations on web pages. However, there is a limitation when it comes to transitioning the display
property. In this tutorial, we will explore why CSS transitions don’t work with the display
property and provide alternative solutions to achieve similar effects.
The display
property is used to define how an element is displayed in the browser. It can take values such as block
, inline
, none
, etc. When an element’s display
property is set to none
, it is removed from the layout, and other elements will adjust to occupy the space.
The reason CSS transitions don’t work with the display
property is that transitioning from display: none
to display: block
or vice versa would require a fundamental change in the element’s rendering mode. This is not something that can be smoothly animated.
One alternative solution is to use the visibility
property instead of display
. The visibility
property only affects the visibility of an element, but it still takes up space in the layout. We can transition the opacity
property to create a fade-in or fade-out effect.
Here is an example:
div {
border: 1px solid #eee;
}
div > ul {
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s linear;
}
div:hover > ul {
visibility: visible;
opacity: 1;
}
Another solution is to use the height
property to create a sliding effect. We can set the height
of an element to 0
and then transition it to its original height when hovered.
div {
transition: height 0ms 400ms, opacity 400ms 0ms;
overflow: hidden; /* Hide the element content, while height = 0 */
height: 0;
opacity: 0;
}
div:hover {
height: 100px; /* any measurable value, not "auto" */
opacity: 1;
transition: height 0ms 0ms, opacity 400ms 0ms;
}
We can also use CSS animations to achieve more complex effects. For example, we can create a fade-in and fade-out animation using keyframes.
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
.parent:hover .child {
display: block;
animation: fadeIn 1s;
}
.parent:not(:hover) .child.did-fade-in {
display: block;
animation: fadeOut 1s;
}
In conclusion, while CSS transitions don’t work directly with the display
property, there are alternative solutions that can achieve similar effects. By using the visibility
, opacity
, and height
properties, we can create smooth animations and transitions on web pages.