Finally transition for display:none
Posted at:
History
A couple of weeks ago, when I was working on my project, I just discover a new CSS feature transition-behavior: allow-discrete;
, this props allows display:none
for transition. This feature is adopted by 89.36% browsers in the world caniuse.com. You no longer need a special tricky trick to handle display:none
animation. You can achieve smooth transitions to discrete properties instead of sudden switches.
The code
Let's create the code. First, create a card with a close button as an example:
<div class="card">
<button class="close">close</button>
</div>
Then, next create CSS to handle style & the most important is the transition:
.card {
position: relative;
width: 200px;
height: 200px;
background-color: #000;
transition: opacity 0.25s, display 0.25s;
transition-behavior: allow-discrete;
}
.fade-out {
opacity: 0;
display: none;
}
.close {
position: absolute;
}
And the javascript to handle event close:
document.querySelectorAll("button").forEach((el) => {
el.addEventListener("click", (e) => {
el.parentElement.classList.add("fade-out");
});
});
By adding transition-behavior: allow-discrete;
, the display: none
will be delayed until opacity
is done.
Final result: