News

CSS image replacement for headers

Posted 10/02/09 by David Web Permalink

Probably the best technique in the world for using CSS to replace header text, with images.

Using images for web page headings can help lift a web design from something quite basic to something much more unique. This can also be used to help maintain your company branding and style using custom graphics and text.

Images should only be inserted using <img> tags when they form part of the content, such as product photos or statistical graphs. Any decorative use of images should be handled using CSS.

For search engine optimisation purposes, a page heading should really use the <h1> tag for maximum affect. So how do you combine the SEO benefits of header tags and the decorative benefits of using images?

Carlsberg slogan aside, there are a wide number of techniques that can be used to replace header text with images. However, none of these seem to offer the perfect solution - which should be able to meet the following requirements.

  • CSS on / Images on
    The default state of most browsers.
  • CSS off / Images on
    The stylesheets have been disabled, so most elements of the page will show as default text.  A perfect solution should still show the desired image.
  • CSS on / Images off
    Images have been blocked so this makes it very difficult to display the desired image rather than normal text.
  • CSS off / Images off
    Neither images or stylesheets are used so displaying the default text is the aim.
  • Additional markup
    Another consideration is the amount of additional code required to produce the solution.  A perfect solution would use no extra markup.

The best solution?

Taking #8 from the list of techniques and making a couple of tweaks you end up with the following code (where title_graphic.gif is the image you want to use with dimensions 270 x 82 pixels)

<h1 class="title" title="Page title goes here"><span></span>Page title goes here</h1>

h1 {
margin:0;
padding:0;
color:#990000;
font:18px georgia,times,serif;
line-height:1.6em;
text-decoration:none;}

h1.title {
width:270px;
height:82px;
position:relative;
overflow:hidden;}

h1.title span {
background: url('media/title_graphic.gif');
position: absolute;
top:0;
width: 100%;
height: 100%;}

This method copes with all the requirements apart from when images are turned off and CSS is on. By applying normal styling to the h1 tag, at least it will revert to nicely styled text.

Another issue with this technique is if the image contains transparencies. As the image is positioned over the text, the text could be visible behind parts of the image.

Conclusion

While not perfect, this technique should work in most cases and uses very little additional markup. Having separate CSS definitions for all your headers will get tiring fast, so for large or dynamic sites using Javascript to assign the background image and styling would be a good idea.