Search code examples
csscss-animations

How can I animate my text to highlight from left to right?


I've been looking for a way to make this work and I can't quite find what I want at this point.

I have this text that I want to highlight, and I would like to animate that to go from left to right. As of now, I've managed to make the highlight appear after a set amount of time, but without the left-to-right effect.

Here's what it looks like right now for reference :

enter image description here

And this is the css I used to make this happen :

@keyframes highlight {
    0% {
        background: none;
    }

    100% {
        background: linear-gradient(to top, $light-purple 50%, transparent 50%);
    }
}

h2 {
    display: inline;
    animation-name: highlight;
    animation-duration: 0.75s;
    animation-fill-mode: forwards;
}

I know this is a very rookie question, but I honestly can't find a way to do it properly, considering what I already have... I would appreciate it if someone could help!

Thanks in advance


Solution

  • I found a solution inspired by this article :

    @keyframes highlight {
        from {
          background-position: 0;
        }
    
        to {
          background-position: -100%;
        }
    }
    
    h2 {
        animation-name: highlight;
        animation-duration: 0.75s;
        animation-fill-mode: forwards;
        background-size: 200%;
        background-image: linear-gradient(to right, white 50%, transparent 50%), 
                          linear-gradient(transparent 50%, purple 50%);
    }
    <h2>Here is an example text that will have the highlight</h2>