Search code examples
htmlcsscss-animationskeyframe

How can I make the text in a span tag slowly disappear and close its gap with CSS?


I created a code with the phrase I am super strong, I used animate from CSS to make the word super slowly fades away, the problem is that I am using position: absolute so the space gap left by the span closes and it does so instantly, while I wanted a effect that slowly closed the gap similar to how I made the span fade away with opacity. Here is a snippet of the code I made:

#title {
  text-align: center;
}

#title > span {
  animation-name: title;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@keyframes title {
  0%   {
    opacity: 1;
  }
  50%  {
    opacity: 0;
    position: static;
    }
  100% {
    opacity: 0;
    position: absolute;
  }
}
<h1 id="title">I am<span> super</span> strong</h1>


Solution

  • You can animate width but not if its initial position is auto. And in this case you won't know how wide the word super is as different fonts/systems/users' rem settings may change it.

    However, you can animate max-width and have that largeish to start with and gradually alter the max-width to 0 once the word has faded away.

    Then to reverse the process (assuming that's what you want to do) the second half of the keyframes can do that. Obviously you will want to alter the timings to take account of this.

    #title {
      text-align: center;
    }
    
    #title>span {
      display: inline-block;
      animation-name: title;
      animation-duration: 8s;
      animation-direction: both;
      animation-iteration-count: infinite;
    }
    
    @keyframes title {
      0% {
        opacity: 1;
        max-width: 40%;
        width: auto;
      }
      25% {
        opacity: 0;
        max-width: 40%;
      }
      50% {
        opacity: 0;
        max-width: 0;
      }
      75% {
        opacity: 0;
        max-width: 40%;
      }
      100% {
        opacity: 1;
        max-width: 40%;
      }
    }
    <h1 id="title">I am<span> super</span> strong</h1>