caramba caramba - 2 months ago 21
CSS Question

CSS transition on child element where parent toggles display property

I read this: SO css-transition-from-display-none-on-class-change but I'm trying to toggle the display property on parent element. Is there a workaround to make it work?

CSS transition works like so
fiddle https://jsfiddle.net/v1aym7wd/

HTML:

<div id="wrap">
<div class="fade"></div>
</div>


CSS:

#wrap {
background-color: orange;
width: 200px;
height: 200px;
/*display: none;*/
}

#wrap.show {
/*display: block;*/
}

.fade {
background-color: green;
width: 100px;
height: 100px;
opacity: 0.2;
transition: opacity 10s;
}

#wrap.show .fade {
opacity: 1;
}


JS:

var wrap = document.getElementById('wrap');
wrap.classList.add('show');


But as soon as I toggle
display:block/none
on parent element the CSS transition does not work. Why is this? Any way to make it work?

See here: https://jsfiddle.net/v1aym7wd/1/

Answer

Since display:none on a parent also takes out descendants from the DOM tree, one solution could be to drop transitions and use animations instead.

The animation will kick in when the child element is displayed.

Do use the necessary vendor prefixes.

.fade {
  opacity: 0.2
}

#wrap.show .fade {
  animation: reveal 10s forwards;
}

@keyframes reveal {
  100% {
    opacity: 1
  }
}

/* set timeout to show how animation starts. */

setTimeout(function reveal() {
  var wrap = document.getElementById('wrap');
  wrap.classList.add('show');
}, 2000);
#wrap {
  background-color: orange;
  width: 200px;
  height: 200px;
  display: none;
}

#wrap.show {
  display: block
}

.fade {
  background-color: green;
  width: 100px;
  height: 100px;
  opacity: 0.2
}

#wrap.show .fade {
  animation: reveal 10s forwards;
}

@keyframes reveal {
  100% {
    opacity: 1
  }
}
<div id="wrap">
  <div class="fade"></div>
</div>

Comments