0

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.

kslstn
  • 1,407
  • 1
  • 14
  • 34
  • Could just hide `#box` and fade in instead? [DEMO HERE](http://jsfiddle.net/Ruddy/3CD7U/2/) Or [DEMO HERE](http://jsfiddle.net/Ruddy/3CD7U/3/) set the others to `display: none` – Ruddy Feb 24 '14 at 11:37
  • That works for opacity change, but doesn't suffice because I want to apply other CSS transitions too, like transform. Moreover, I would like to have all styling in my CSS rather than in the scripts. – kslstn Feb 24 '14 at 11:42

1 Answers1

0

It seems that instead of using the visibility rather than the display property is the solution.

visibility: hidden;

Arguably it's even better for rendering performance. It also works in all modern browsers (IE 4+).

Community
  • 1
  • 1
kslstn
  • 1,407
  • 1
  • 14
  • 34