Search code examples
csscss-animationsstyled-components

How can I style the first letter and apply this linear gradient animation?


I have some code using background-position and a linear-gradient in order to create a swiping right animation when you hover the text.

div {
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-image: linear-gradient( to right, #8b73f6, #8b73f6 50%, #000 50%);
  background-size: 200% 100%;
  background-position: 100%;
  font-size: 1.5rem;
  display: inline-block;
  transition: all 0.3s cubic-bezier(0, 0, 0.23, 1);
}

div:hover {
  background-position: 0%;
}
<div>Baz</div>

I want to combine this with the ability to color the first letter of my element so that the first letter is colored then on hover the rest is colored.

I used the ::first-letter pseudo-element and was able to change the color to purple that way:

  div::first-letter {
    color: #8b73f6;
  }
<div>Foo</div>

But, when I combine these, the linear-gradient always wins out and sits on top of my color. I could change the background-position on the div until it only shows color on the first letter, but then the solution only works for that specific letter because I'm not using a monospace font.

Here is my attempt at combining them:

div {
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-image: linear-gradient( to right, #8b73f6, #8b73f6 50%, #000 50%);
  background-size: 200% 100%;
  background-position: 100%;
  font-size: 1.5rem;
  display: inline-block;
  transition: all 0.3s cubic-bezier(0, 0, 0.23, 1);
}

div::first-letter {
  color: #8b73f6;
}

div:hover {
  background-position: 0%;
}
<div>Bar</div>

As an aside, I'm incorporating this using styled-components. Any ideas would be much appreciated!


Solution

  • Got it working as such! I just needed to stop using -webkit-text-fill-color and use normal color. This answer pointed me in the right direction.

    div {
      -webkit-background-clip: text;
      color: transparent;
      background-image: linear-gradient( to right, #8b73f6, #8b73f6 50%, #000 50%);
      background-size: 200% 100%;
      background-position: 100%;
      font-size: 1.5rem;
      display: inline-block;
      transition: all 0.3s cubic-bezier(0, 0, 0.23, 1);
    }
    
    div::first-letter {
      color: #8b73f6;
    }
    
    div:hover {
      background-position: 0%;
    }
    <div>Foo</div>