Jens Törnell
Jens Törnell

Reputation: 24768

Display none after css animation ended

I have a working animation that starts on load with pure CSS. The problem with both opacity and visibility is that even if the div is hidden, it still takes up space.

Question

How can I make the div disapear like display: none after the animation is done?

Notes

.message.success {
  background: #28a745;
  color: #fff;
  animation: autohide 2s forwards;
  padding: 1rem;
}

@keyframes autohide {
  0% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<div class="message success">
  Success!
</div>

This text below is expected to jump up after animation is done.

Upvotes: 0

Views: 326

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

You could set to zero the padding and the font-size at the last keyframe

.message.success {
  background: #28a745;
  color: #fff;
  animation: autohide 2s forwards;
  padding: 1rem;
}

@keyframes autohide {
  0% {
    opacity: 1;
  }
  85% {
    opacity: 1;
  }
  95% {  
    opacity: 0;
    padding: 1rem;
    font-size: inherit;
  }
  100% {
    padding: 0;
    font-size: 0;
    opacity: 0;
  }
}
<div class="message success">
  Success!
</div>

This text below is expected to jump up after animation is done.

Upvotes: 1

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4764

You could use the height property to achieve this effect:

@keyframes autohide {
  0% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  99% {
    height: auto;
    padding: 1rem;
  }
  100% {
    opacity: 0;
    height: 0;
    padding: 0;
  }
}

height is kept auto until near the end of the animation (99%), then set to 0 as it completes.

Upvotes: 1

Awais
Awais

Reputation: 4902

There you go i think this is what you want.

By giving height to 0 works perfectly with transition

.message.success {
  background: #28a745;
  color: #fff;
  animation: autohide 2s forwards;
  transition: height 2s ease;
}

@keyframes autohide {
  0% {
    opacity: 1;
    height: auto;
  }
  90% {
    opacity: 1;
    height: auto;
  }
  100% {
    opacity: 0;
    height: 0;
  }
}
<div class="message success">
  Success!
</div>

This text below is expected to jump up after animation is done.

You can play with transition as per req.

Upvotes: 0

Related Questions