I want to show a modal window (div) with a grey background (parent div). For reasons I don't understand, a transition applied to the modal window only works when the parent's element's display property isn't changed.
The transition should be shown because there is a CSS transition applied to opacity and I changed the opacity to 1 by adding the class 'show'.
The opacity is correctly changed: my window is visible. No transition is shown, however.
Fiddle: http://jsfiddle.net/3CD7U/1/
HTML
<button id="button">click me</button>
<div id="background">
<div id="box">
<h1>Modal window</h1>
<p>I'd expect to see a transition when adding the show class. Unfortunately, the transition is only shown when the parent's display property isn't changed at the same time.</p>
<p id="show-later">Here the transition is applied correctly, because of a delay. To work reliably however, the delay seems to have to be over 100ms, making the UI seem sluggish.<p>
</div>
</div>
CSS
#background{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: silver;
}
#box{
position: relative;
width: 50%;
margin-top: 30px;
margin-left: auto;
margin-right: auto;
padding: 20px;
background: white;
border: 1px solid grey;
opacity: 0;
}
#show-later{
opacity: 0;
}
#box.show,
#show-later.show{
opacity: 1;
transition: opacity 500ms linear;
}
JQuery
$("#background").hide();
$("#button").click( function(){
$("#background").show();
$("#box").addClass("show");
setTimeout( function(){
$("#show-later").addClass("show");
}, 2000);
})
I don't want to rely on changing the opacity only, because old browsers.
I've seen other websites with modal windows with transitions, but I can't figure out why those work and my fiddle not.
I have a workaround: adding a class that includes an animation the moment the modal window has to be shown, but it's not as clean as just applying/removing CSS classes with transitions.
Ideas for how to correctly add transitions to elements that change from display:none are welcome.