I recently had cause to transition display: none. It's not yet working in all browsers, but when I tried it I found the effect was so subtle that no one would notice the difference. In this example I had to change the transition time to 1 second in order to see it.
The HTML
<div>
<p>Some text here</p>
<span></span>
</div>
<button>Toggle active state</button
Some JS to add the transition
const button = document.querySelector('button');
const div = document.querySelector('div');
button.addEventListener('click', function() {
div.classList.toggle('is-active');
})
The CSS
body {
display: flex;
align-items: flex-start;
gap: 20px;
}
div p {
margin-bottom: 4px;
}
div span {
width: 100%;
height: 4px;
background: red;
display: none;
opacity: 0;
transition: opacity 1s, display 1s allow-discrete;
}
div.is-active span {
display: block;
opacity: 1;
@starting-style {
opacity: 0;
}
}
button {
padding: 0.5rem 1rem;
}
The transition
A lot of that CSS is the set up, the transition bits we’re interested in are these bits:
div span {
display: none;
opacity: 0;
transition: opacity 1s, display 1s allow-discrete;
}
div.is-active span {
display: block;
opacity: 1;
@starting-style {
opacity: 0;
}
}
Most of this is pretty standard. The span starts off with an opacity of 0 and display: none. The transition transitions opacity in 1s. And also display - which works because of the allow-discrete keyword.
And then when the is-active class is applied to the parent div we change it to be an opacity of 1 and display: block.
The thing that actually makes this all work is this bit:
@starting-style {
opacity: 0;
}
This tells it that it's starting from an opacity of 0. You’d think it would know that because I told it it had an opacity of 0 when the is-active class is applied. But it needs to know within the is-active class too, so it knows how to transition the opacity in. If you remove this it will transition out, but not in. It's as if now the is-active class is applied it can no longer see the styles set on the div and you have to let it know what they are.
Codepen decided not to run JS when I set this up, so here's a JSFiddle instead.
Top comments (0)