How do I combined CSS text-shadow and “background-image: -webkit-gradient”

假装没事ソ 提交于 2019-12-03 05:07:22

The gradient "disappears" because the text-shadow is on a level above the background.

  1. The text (which is transparent)
  2. The shadow
  3. The background.

We can work around this by copying the text and put it below the original layer, then apply the shadow there, for example:

  h1 {
    position: relative;
    font-size: 100px;
    text-align: center;
  }

  h1 div {
    background-image: -webkit-gradient(linear, left top, left bottom, from(white), to(black));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    position: absolute; 
    width: 100%;
}
  h1:after {
    text-shadow: 10px 10px 11px #fff;
    color: transparent;
  }

  #hello:after {
        content: 'Hello World';
  }
  <h1 id="hello"><div>Hello World</div></h1>
Michael

This answer is similar to the answer by @KennyTM above, except his answer has the shadow hard-coded into the CSS, which is not suitable for dynamic text such as in a CMS. Also, his method requires a separate ID for each instance, which would be very tedious if you plan to use this effect a lot. The example below uses a class instead, and allows dynamic text.

Try this:

h1 {
    position: relative;
    font-size: 100px;
    text-align: center;
}

h1 div {
    background-image: -webkit-gradient(linear, left top, left bottom, from(teal), to(black));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    position: absolute; 
    width: 100%;
}
h1:after {
    text-shadow: 2px 2px 2px #000000;
    color: transparent;
}

.gradient-shadow:after {
    content: attr(title); /* Pulls the text from the 'title' attribute to make the shadow */
}

And then in your HTML:

<h1 class="gradient-shadow" title="Hello World"><div>Hello World</div></h1>

Just make sure that the text in the <div> matches the text in the title attribute.

With some additional formatting (I used Helvetica Neue Ultralight and a dark background), you can get an effect something like this: http://cl.ly/image/2C0k0I3W271D

With no extra HTML markup or pseudo elements you can achieve this effect using the filter property and drop-shadow function. This method also works with a background image vs gradient.

h1 {
  font:54px 'Open Sans', 'Helvetica', Arial, sans-serif;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#787878), to(#484848));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  -webkit-filter: drop-shadow(2px 2px #333);
          filter: drop-shadow(2px 2px #333);
}

Fiddle: https://jsfiddle.net/eywda89g/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!