CSS Gradient Text

by Jigar Panchal on 18/11/2008 · 0 comments

in CSS,Design

Benefits

  • This is pure CSS trick, no Javascript or Flash. It works on most browsers including IE6 (PNG hack required).
  • It is perfect for designing headings. You don’t have to render each heading with Photoshop. This will save you time and bandwidth.
  • You can use on any web fonts and the font size remains scalable.

How does this work?

The trick is very simple. Basically we are just adding a 1px gradient PNG (with alpha transparency) over the text.

CSS Gradient Text Effect image 1

The HTML markups

<h1><span></span>CSS Gradient Text</h1>

The CSS

The key point here is: h1 { position: relative } and h1 span { position: absolute }

h1 {
font: bold 330%/100% “Lucida Grande”;
position: relative;
color: #464646;
}
h1 span {
background: url(gradient.png) repeat-x;
position: absolute;
display: block;
width: 100%;
height: 31px;
}

That’s it! You are done. Click here to view my demo page.

Make it work on IE6

Since IE6 doesn’t render PNG-24 properly, the following hack is required in order to display the transparent PNG (add anywhere in between the <head> tag):

<!–[if lt IE 7]>

<style>
h1 span {
background: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’gradient.png’, sizingMethod=’scale’);
}
</style>

<![endif]–>

This is why we hate IE 6!

jQuery prepend version (for semantic lovers)

If you don’t want to have the empty <span> tag in the heading, you can use Javascript to prepend the <span> tag. Here is a sample using jQuery prepend method:

<script type=”text/javascript” src=”jquery.js”></script>

<script type=”text/javascript”>
$(document).ready(function(){

//prepend span tag to H1
$(“h1″).prepend(“<span></span>”);

});
</script>

More samples

Want to make Web 2.0 glossy text?

CSS Gradient Text Effect image 2

Literally, you can apply this trick on any solid background color (as long your gradient color is the same as your background color).

CSS Gradient Text Effect image 3

CSS Gradient Text Effect image 4

CSS Gradient Text Effect image 5

CSS Gradient Text Effect image 6

CSS Gradient Text Effect image 7

CSS Gradient Text Effect image 8

Pattern / Texture

You can also apply this trick with a tile background image. Look, here is an example of zebra pattern. So, be creative!

CSS Gradient Text Effect image 9

Limitations and more…

  • This trick is only suitable for solid background color elements. Your gradient color (PNG image) must be the same color as your background color.
  • IE PNG hack is required if you want it to work on IE 6.
  • If your gradient image is taller than the heading, the text will not be selectable.

Previous post:

Next post: