开发者

How can I do text gradient in CSS without affecting background?

开发者 https://www.devze.com 2023-02-15 13:18 出处:网络
I would like to use a text gradient on my headers (this type of effect, basically). Commonly, this is achieved using png alpha-transparent image over the text. My problem with this solution is that wi

I would like to use a text gradient on my headers (this type of effect, basically). Commonly, this is achieved using png alpha-transparent image over the text. My problem with this solution is that within the header box alpha transparency will also influence the backgro开发者_C百科und. So if, for example, I wanted to use a photo as a background of my headers it would look awful. Is there a way around this (at least in some browsers, for starters).


There isn't a way to do this with CSS3 - even the CSS3 Image Values and Replaced Content Module, though it contains lots of cool stuff to do with gradients, only lets you use them where you would be able to use an image, not as a colour.

However, SVG does let you do this, though taking advantage of it in HTML is a bit of work. First, create the SVG document with your gradient text in it. You'll need a gradient:

<defs>
    <linearGradient id="heading_gradient" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" style="stop-color:rgb(0,0,0); stop-opacity:1"/>
        <stop offset="100%" style="stop-color:rgb(0,0,0); stop-opacity:0.1"/>
    </linearGradient>
</defs>

And some text to apply it to, notice the fill attribute:

<text x="0" y="100"
    font-family="sans-serif" font-weight="bold"  fill="url(#heading_gradient)" >
    <tspan font-size="100">A Big Heading</tspan>
</text>

Then you need to include the SVG in your HTML.

<h1>
    <object data="heading-fill.svg" type="image/svg+xml" height="125" width="800">
        A Big Heading
    </object>
</h1>

Note that with no SVG support the heading should fall back to the content contained within the object tag and everything should be accessible (I haven't checked). Then set up the CSS so the fallback content should match the SVG and add the background image:

h1 {
    font-size: 100px;
    font-family: sans-serif;
    background-image: url('daisy-grass-repeating-background.jpg');
}

There's a full example here, works for me in Firefox 3.6/4, Chromium and Opera 11.01. It isn't actually very readable, but I'll leave the fine tuning to you ;) Depending on what browsers you want to support you may need to investigate embed instead of object.


If you're only using it in a few places, you could simply use image replacement:

#the-h1
{
  background: url('the-h1.png') no-repeat left top;
  height: 1em;
  text-indent: 9001px;//it's over 9000
  overflow: hidden;
}

It's not a nice solution as you'll have to make an image for each header you want to replace, but it does have the benefit of being able to enforce a very specific font and style.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号