Search code examples
htmlcssshadow

How to have Text-Shadow with Webkit gradient


When I use Text-Shadow with Webkit gradient, it appears to be on top of the text - instead of behind. I increased the shadow opacity to show this.

#title {
  font-size: calc(15px + 9vw);
  text-align: center;
  background: linear-gradient(to right, red 0%, blue 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-top: 8vh;
  text-shadow: -10px 15px 5px rgba(0,0,0,0.1),
                 -10px 20px 5px rgba(0,0,0,1),
                 -10px 20px 5px rgba(0,0,0,1);
}
<h3 id="title">Example</h3>


Solution

  • And idea is to create another layer with pseudo-element that you put behind.

    #title {
      font-size: calc(15px + 9vw);
      text-align: center;
      background: linear-gradient(to right, red 0%, blue 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin-top: 8vh;
      position:relative;
    }
    #title:before {
      content:attr(data-text);
      position:absolute;
      top:0;
      right:0;
      left:0;
      bottom:0;
        text-shadow: -10px 15px 5px rgba(0,0,0,0.1),
                     -10px 20px 5px rgba(0,0,0,1),
                     -10px 20px 5px rgba(0,0,0,1);
      z-index:-1
    }
    <h3 id="title" data-text="Example">Example</h3>

    And if you don't want to duplicate the text you can use both pseudo-element and define the text only in the attribute:

    #title {
      position: relative;
      text-align: center;
      margin-top: 8vh;
      font-size: calc(15px + 9vw);
      z-index: 0;
    }
    
    #title:before {
      content: attr(data-text);
      position: relative;
      background: linear-gradient(to right, red 0%, blue 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      z-index: 1;
    }
    
    #title:after {
      content: attr(data-text);
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      text-shadow: 
        -10px 15px 5px rgba(0, 0, 0, 0.1), 
        -10px 20px 5px rgba(0, 0, 0, 1), 
        -10px 20px 5px rgba(0, 0, 0, 1);
      z-index: -1;
    }
    <h3 id="title" data-text="Example"></h3>