cssreactjscss-animationsopacityletter-spacing

Fading out a span with css animations leaves space


I want to animate some text, that is located in the middle of more text. Everything works almost fine, except the faded out span leaves additional space in it's place that looks kinda ugly. Setting in the "faded out" part of the animation display: none or width: 0 doesn't help

Edit: I feel obligated to point out after the first answer: the spans are there for additional styling reasons, it's just that additional fluff is removed to simplify the example. Also, there are no spaces in the animated part so you can see that space I don't need more clearly to avoid confusion. In real life everything is more complex and nice-looking.

After I posted the question I found some exhaustive info on the problem in HTML: How do I remove the space between inline-block elements? or off-site.

Unfortunately, my problem is, I'm in React. Nominally it solves that by itself, as I've found out here: Remove space between inline-block elements in React

But it seems I've caught some weird bug with that darn whitespace behaving inconsistently (see snippet for example). I guess I'll have to go to React to report it.

const MyComponent = () => {
    return (<div>      
      <span>Static text</span>
      <span className="animation">Word</span>
      <span>More static text</span>          
      <br />
      <span>Static text</span>
      <span className="animation">Several Words</span>
      <span>More static text</span>          
    </div>
    );
}
    
  ReactDOM.render(<MyComponent />, document.getElementById('root'));
.animation {
    animation: animation 7s linear infinite both;
}

@keyframes animation {
    0%,
    40%,
    100% {
        letter-spacing: initial;
        display: initial;
        opacity: 1;
    }

    50%,
    90% {
        letter-spacing: -0.5em;
        display: none;
        opacity: 0;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


Solution

  • Turns out, the issues I'm mentioning in the question aren't at fault here, it just looks like they are. The actual problem is with letter-spacing that the animation sets, and the 0 opacity just makes it look like it's whitespace. Here is a demo with higher opacity so you can see what's happening:

    .styled {
      letter-spacing: -0.5em;
      opacity: 0.1;
    }
    <span>Static span</span><span class="styled">WWWWW</span><span>Static span</span>
    <br/>
    <span>Static span</span><span class="styled">iiii</span><span>Static span</span>

    Setting the letter-spacing to -1em solves the issue, but I'll have to fiddle around with the animation so it looks as nice as it was.