2

I'm trying to create a text highlight animation in css like the one in this gif. From left to right continuously. enter image description here

I tried this

<p>
The <span class="test">world</span>
</p>


.test {
  background: linear-gradient(to top, red 50%, transparent 50%);
  animation-name: highlight;
  animation-duration: 1s;
  animation-iteration-count: infinite;
}

@keyframes highlight {
  0% {
    background-size: 0;
    background-position: -100%, 0;
  }

  50% {
    background-size: 100%;
    background-position: 100%, 100%;
  }
}

But it's giving some weird glitch effect instead. What am I doing wrong and how to achieve this?

Bluebug
  • 294
  • 4
  • 13

1 Answers1

4

You will need to use a pseudo element (preferably :after) and play around with the width of that pseudo element.

.test {
  position: relative;
}
.test:after {
  content: "";
  display: inline-block;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1; /* Place the pseudo element right under the content */
  top: 0;
  left: 0;
  background: linear-gradient(to top, red 50%, transparent 50%);
  animation-name: highlight;
  animation-duration: 0.75s;
  animation-iteration-count: infinite;
  animation-direction: alternate; /* Make the animation run back and forth */
}

@keyframes highlight {
  0% {
    width: 0;
    opacity: 0;
  }

  50% {
    width: 100%;
    opacity: 1;
  }

}
<p>
The <span class="test">world</span>
</p>

References:

Pseudo elements :after

Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
  • Wow cool man. I thought of using the ::before element but didn't get this far. Thanks a lot! – Bluebug Oct 04 '20 at 17:12
  • Hi, as I'm reading your answer again, I have a question (I'm new to this). Wouldn't ending the keyframes element at 50% be same as the animation-direction? i.e. it will repeat itself...? – Bluebug Oct 05 '20 at 18:08
  • @Bluebug you can try disabling the animation-direction and check the resulting effect. – Kostas Minaidis Oct 06 '20 at 11:17
  • Ah so I was mistaken. Setting the last keyframes at 50% does nothing but speeding it up (2x). The direction is actually rolling it back. – Bluebug Oct 07 '20 at 19:49
  • 1
    Exactly! Try spending some time to learn about the CSS animation properties and play around with different code variations. – Kostas Minaidis Oct 08 '20 at 12:47
  • Will do. Thanks mate. ️ – Bluebug Oct 08 '20 at 19:03