Bluebug
Bluebug

Reputation: 295

How to auto-animate text highlight in css?

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?

Upvotes: 2

Views: 7562

Answers (1)

Kostas Minaidis
Kostas Minaidis

Reputation: 5437

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

Upvotes: 4

Related Questions