CSS animations are fundamental to modern web development. But one of the biggest problems in CSS has been animating the property display: none
.
So far, it has not been possible to animate this property because it is a sort of switch, either on or off. So far...
Yes, because there are currently some tricks to be able to create animations with display: none
and you can use them from now.
A new way to animate display: none
At first glance it looks like a normal transition effect with opacity. But if you look closely at the code there are some features to consider.
This is the code we are going to inspect:
.block {
display: none;
max-width: 500px;
margin: 50px auto 0;
width: 100%;
background-color: #29C38A;
color: #fff;
opacity: 0;
padding: 20px;
box-sized: border-box;
transition: opacity .3s ease,
display .3s ease allow-discrete; /* <-- check this line */
&.open {
opacity: 1;
display: block;
}
}
@starting-style { /* <-- and this line */
.block.open {
opacity: 0;
}
}
transition-behavior: allow-discrete
The transition-behavior: allow-discrete
property manages how discrete properties like display
and content-visibility
animate. Normally, these properties flip values at the 50% mark of an animation. However, when transitioning to or from display: none
or content-visibility: hidden
, the content remains visible throughout, flipping to the visible state at 0% or to none
at 100%.
@starting-style
The @starting-style
CSS rule is used to enable transitions on an element's first appearance or when its display changes from none
to another value. Normally, CSS transitions don't trigger on initial style updates, so @starting-style
defines the starting values for properties to transition from.
This rule is especially useful for creating smooth entry and exit animations for elements like popovers, modals, or anything added or removed from the DOM. It can be used as a standalone block or nested within an existing ruleset. The @starting-style
ensures that the element transitions from the specified starting values when it first appears.
Conclusion
Using transition-behavior: allow-discrete
and @starting-style
opens up new possibilities for animating elements that were previously challenging, like those with display: none
. These tools make it easier to create smooth and visually appealing transitions, improving the user experience without needing complicated workarounds. By allowing seamless animations when elements first appear or disappear, they bring more flexibility and control to web design, making your interfaces more dynamic and engaging.