s

Better Text Replacement with CSS

Apr 16, 2009

There are several methods for rendering non-web fonts (eg. Cufón and sIFR). Both are tedious to set up and implement. The easiest alternative is the good old image-instead-of-text trick, but that's not good for SEO, even with alt tags.

There is a way to have SEO text AND use an image as the text. With a little CSS trickery, you can easily achieve the desired effect. Worth noting, however, is that this method is really only good for non-dynamic, fixed width text (such as headings). It's not practical for blocks of text.

The first thing you need is an image for the text you want to replace (and yes, I'm using Comic Sans):

Now for the html code that we'll be working with:

<h1 class="replace heading">My Heading</h1>

The CSS does all the work.

.replace {
  display:block;
  height:0;
  overflow:hidden;
  font-size:0;
  letter-spacing:-1em;
  text-indent:-1000em;
}
.heading {
  width:135px;
  padding:26px 0 0 0;
  background:url('/images/custom_header.png') no-repeat 0 0;
}

First, we make the h1 virtually invisible via CSS by assigning a height and font-size of 0. Then we make sure it's invisible in all browsers by setting the letter-spacing and text-indent. The heading class has a top-padding which creates just enough space to show the image, which we set as the background. Super easy and effective!

You'll notice that I made two classes. I use the replace class as a global for the styles that are common to all replaced text, then the heading class has the unique styles.

Tagged: csstutorialtext replacement