0

CSS transitions will not apply if you set the display property of an element to block immediately before changing the property with the transition attached. You can see the issue in the following example:

var dom = {};
dom.creative = document.getElementById('creative');
dom.creative.style.display = 'block';
dom.creative.style.opacity = 1;
#creative {
    display: none;
    opacity: 0;
    transition: opacity 2s; 
}
<div id="creative">
    <span>Sample text</span>
</div>

The issue can be fixed by forcing a repaint on the element:

    var dom = {};
    dom.creative = document.getElementById('creative');
    dom.creative.style.display = 'block';
    var a = dom.creative.offsetHeight; /* <-- forces repaint */
    dom.creative.style.opacity = 1;
#creative {
    display: none;
    opacity: 0;
    transition: opacity 2s; 
}
<div id="creative">
    <span>Sample text</span>
</div>

This solution is not good because it adds the need of a non intuitive extra line of code everytime you need the display transition combination.

A SO user found an elegant solution (https://stackoverflow.com/a/38210213/6004250) to this problem replacing the transition by the animation property. I'm still curious about making it work together with CSS transitions (because they are easier to understand and to use). Any ideas?

Community
  • 1
  • 1
incompleteness
  • 260
  • 1
  • 12
  • `display: none` make element take no space in the rendered output, when toggle to `block` it does. Is that the effect you want, hence the need of switching between the two? ... Or you just simply is looking for a method that does repaint an element? – Asons Jul 05 '16 at 22:14
  • Yes, that is the effect I want. Simple because it is a very very common scenario. – incompleteness Jul 05 '16 at 22:44
  • Then check my newly added 3:rd sample in the previous question, it uses height/width to achieve that effect – Asons Jul 05 '16 at 22:48

0 Answers0