css 动画结束后显示 none

Display none after css animation ended

我有一个工作动画,它以纯 CSS 加载开始。 opacityvisibility的问题是,即使隐藏了div,它仍然占用了space。

问题

如何让div在动画完成后像display: none一样消失?

备注

.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.

好了,我想这就是你想要的。

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.

你可以按照要求玩转场

您可以使用 height 属性 来实现此效果:

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

height 保持 auto 直到接近动画结束 (99%),然后在它完成时设置为 0

您可以将最后一个关键帧的填充和字体大小设置为零

.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.