-1

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

almecin
  • 41
  • 5
  • can you provide a working example please? – Sfili_81 Dec 15 '21 at 14:05
  • Does this answer your question? [Animating Linear Gradient using CSS](https://stackoverflow.com/questions/23441060/animating-linear-gradient-using-css) – Sfili_81 Dec 15 '21 at 14:07
  • If possible, I would recommend adding enough code to constitute a [mcve], preferably as a runnable snippet, along with steps to reproduce the issue. This will go a long way in enabling the community to provide you with helpful direction. Good luck, and happy coding! – Alexander Nied Dec 15 '21 at 14:45

1 Answers1

3

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>
Tom
  • 4,972
  • 3
  • 10
  • 28
  • Thank you! This works wonders. My only problem is that I would love to keep the highlight like at 50% of the text height, just like in the picture I put. Which, with your solution, is impossible for me since I use linear-gradient to top to do that. Any ideas how I could still achieve that ? Thanks! – almecin Dec 15 '21 at 16:27
  • @almecin I think you could set a white color that hides the highlight color like `background-image: linear-gradient(to left, white 50%, transparent 50%), linear-gradient(transparent 50%, red 100%);` and then this animation would slide the white color and reveal the highlight color. This would require you to set the background initial color according to where the text is. – aerial Dec 15 '21 at 17:02
  • I updated my answer using the code of @aerial301 – Tom Dec 15 '21 at 17:26
  • @aerial301 Thanks to the both of you!! – almecin Dec 15 '21 at 22:23