Search code examples
htmlcsscss-animations

Animated CSS strikethrough text decoration with multiple text colors


I'm referring to this answer. What if there is more than one color needed to be strikethrough?

span {
  background: 
    linear-gradient(red 0 0) no-repeat 
    0 60% / var(--s,0%) .1em,
    #000;
  -webkit-background-clip: border-box, text;
          background-clip: border-box, text;
  color: #0000;
  transition: background-size .4s ease;
  font-size: 1.5em;
}

span:hover {
  --s: 100%;
}
<span>
  <a href="#">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</a> At vero eos et accusam et justo duo dolores et ea rebum.
</span>


Solution

  • Not many changes are needed. Just replace the background's #000 fallback color with the currentcolor and add a -webkit-text-fill-color entry in place of color.

    While color changes all of the text, -webkit-text-fill-color affects only the parts that overlap what was clipped with background-clip (the strikethrough line). I prefer transparent over #0000, but they are technically identical (#0000 is black but with zero opacity, which is transparent, just like #fff0).

    span, span * {
      background: 
        linear-gradient(red 0 0) no-repeat 
        0 60% / var(--s,0%) .1em,
        currentcolor;
      background-clip: border-box, text;
      -webkit-text-fill-color: transparent;
      transition: background-size .4s ease;    
      font: bold 1.5rem serif;
    }
    
    span:hover {
      --s: 100%;
    }
    <span>
      <a href="#">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</a> At vero eos et accusam et justo duo dolores et ea rebum.
    </span>

    I've made the text bold so you can more clearly see that the strikethrough line is rendered atop the text. I changed the units to ensure it's not as relative; span, span * { font-size:1.5em } would mean children are half again as big as the container. 1.5rem is instead relative to the document root.

    (You may notice that I've removed -webkit-background-clip and I don't include text-fill-color or -moz-text-fill-color. That's because background-clip is now fully supported without a vendor prefix and text-fill-color isn't (yet?) a proposal; it's supported only with the -webkit vendor prefix, even on Firefox.)