tldr: You cannot use the transition
property with the display
property. And yes, you can't use the transition
property on any other css property of an element whose's current display
property is none
either.
The cleanest workaround for this would be to simultaneously transition the width
property and the opacity
property together.
Check this JSFiddle to see how you can use the width
and height
property to replicate the display:none
property of not letting the element take any space in the document flow.
The <span>
element is just for demonstrating how the <p>
tag does not take any space while it's hidden.
You can also check out the code in the following Snippet but as you mentioned, the transition doesn't work here for some weird reason.
var p = document.getElementsByTagName("p")[0];
p.style.width = "50%";
p.style.height = "auto";
p.style.opacity = 1;
html, body{width: 100%; height: 100%; margin: 0; padding: 0;}
p {
width: 0;
height:0;
opacity: 0;
transition: width 2s, opacity 3.5s;
float:left;
margin: 0;
}
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis culpa nobis dolorem voluptates ut odio numquam officia provident quos labore, natus sint doloribus ducimus similique aspernatur, enim, voluptatibus vel facere!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, adipisci? Quidem laboriosam sunt, qui non ea placeat laborum deserunt consequatur consequuntur vel, officiis magnam. Vitae officiis, quidem doloribus nesciunt voluptatem!
</p>
<span>Right side text</span>
But if you have to use display:none
, then as shown in this css article, you can just use the setTimeout()
workaround to set the transition property after the display property is toggled instead of during the display property toggling like this:
var p = document.getElementsByTagName("p")[0];
p.style.display = "block";
setTimeout(function(){p.style.opacity = 1;},1000);
p {
display: none;
opacity: 0;
transition: opacity 1s;
}
<p>
Lorem ipsum...
</p>