Search code examples
htmlcsscss-animationsfade

CSS fade-out and stay so


Is there a CSS only way to fade-out this text as below and have it stay hidden once the animation completes? It currently fades out, then appears again. I have tried adding display: none (as well as height: 0px, which isn't really what I want), but the issue remains - it re-appears once the animation completes.

Happy to use some JavaScript to do this (there is a stack overflow answer explaining how to listen out for the end of the animation event), but pure CSS is preferred.

.fade-out {
  animation: fadeOut ease 5s;
  -webkit-animation: fadeOut ease 5s;
  -moz-animation: fadeOut ease 5s;
  -o-animation: fadeOut ease 5s;
  -ms-animation: fadeOut ease 5s;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@-moz-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@-webkit-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@-o-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

@-ms-keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<h1 class="fade-out">hello</h1>


Solution

  • Use animation-fill-mode: forwards; for that purpose:

    .fade-out {
      animation: fadeOut ease 5s;
      animation-fill-mode: forwards;
    }
    
    @keyframes fadeOut {
      0% {
        opacity: 1;
      }
      100% {
        opacity: 0;
      }
    }
    <h1 class="fade-out">hello</h1>