Smitha
Smitha

Reputation: 6134

Display none in CSS fade out does not work or hide the div

I have the following CSS transition -

fadeinout-animate {
    width:200px;
    height: 200px;
    background: red;
    -webkit-animation: fadeinout 4s linear forwards;
    animation: fadeinout 4s linear forwards;
    opacity: 0;
}

@-webkit-keyframes fadeinout {
  50% { opacity: 1; }
}

@keyframes fadeinout {
  50% { opacity: 1; }
}
@keyframes fadeinout {
  100% { opacity: 0;display:none; }
}

But, when I add this class to a div in Angular template, display none works but a blank space of 200*200 stays as is. (If I inspect element I still see that the red background alone is gone but manually applying display none inline style in browser hides or removes div) If i make height:0 that div goes off but it impacts behavior. How do I fix it?

Upvotes: 4

Views: 15331

Answers (2)

Keith
Keith

Reputation: 24211

To add to @Highdef answer,.

If you don't mind adding a bit of Javascript, you can listen for the animation end event, and set display none manually.

const e = document.getElementById("a");
e.addEventListener("animationend", (ev) => {
  if (ev.type === "animationend") {
    e.style.display = "none";
  }
}, false);
#a {
  width: 200px;
  height: 200px;
  background: red;
  -webkit-animation: fadeinout 4s linear forwards;
  animation: fadeinout 4s linear forwards;
  opacity: 0;
}

@keyframes fadeinout {
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<div style="border:1px solid black;width:200px;">
  <div id="a">
  </div>
</div>

Upvotes: 3

user7207170
user7207170

Reputation:

CSS can't animate between display: none; and display: block;. Worse yet: it can't animate between height: 0 and height: auto. So you need to hard code the height.

Here's an attempt with CSS:

Expected: the border should collapse but will it?

#a {
  width: 200px;
  height: 200px;
  background: red;
  -webkit-animation: fadeinout 4s linear forwards;
  animation: fadeinout 4s linear forwards;
  opacity: 0;
}

@keyframes fadeinout {
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    display: none;
  }
}
<div style="border:1px solid black;width:200px;">
  <div id="a">
  </div>
</div>

Output: No, it won't.

Now, lets try this..

#a {
  width: 200px;
  height: 200px;
  background: red;
  -webkit-animation: fadeinout 4s linear forwards;
  animation: fadeinout 4s linear forwards;
  opacity: 0;
}

@keyframes fadeinout {
  50% {
    opacity: 1;
  }
  99% {
    opacity: 0;
    height: 200px;
  }
  100% {
    height: 0px;
  }
}
<div style="border:1px solid black;width:200px;">
  <div id="a">
  </div>
</div>

So, we basically collapsed the div after its transition was over by reducing its height to 0 and thus the parent container tag collapsed.

Upvotes: 6

Related Questions