Mr eel

CSS - Image Replacement Hot Melon Jam Fu

There are loads of image replacement techniques and I think I’ve experimented with most of them. More recently I’ve hit on a set of rules that are pretty bulletproof and thankfully don’t require any kind of hacks.

It hinges on using the letter-spacing rule — big ups to Beej for putting me onto that one. The basic idea is that you set the letter spacing to a negative value. The text essentially collapses and disappears. The best part is that the element doesn’t otherwise change. It still keeps it’s width, height and positioning. You can now freely change the height or width without having to make hacks to accommodate Internet Explorer’s horrible rendering engine.


.imageReplacement {
  background:left top no-repeat url(/images/heading.gif);
  letter-spacing:-1000em;
  text-indent:-1000em;
  width:250px;
  height:70px;
}

There are two quirks to look out for here. Firstly the letter spacing has to be -1000em. After experimentation, other more patient people have discovered that it is the value that works reliably across most browsers. Secondly, the text-indent is there to hide the text in Safari and early version of IE, where the letter-spacing rule does not correctly apply. It forces the text to sit outside the container, so it disappears. Using both text-indent and letter-spacing together means you’ll hide the text reliably in most browsers.

I’m not sure it’s the Holy Grail of image replacement, but it’s pretty good!

P.S. .imageReplacement is a horrible class name. I only use it as an example. I prefer to use class names that refer to what the element is and what it does, rather than how it looks. Much easier to modify later on.

Posted on November 30th, 2007 | There are 2 comments

Comments

beej on December 2, 2007

Big ups to stuffandnonsense which is where I learned of it pinched it from in the first place!

beej on December 2, 2007

and damn your stripping of deprecated strikethroughs which render my comment nigh on unintelligible!

Add a comment

All contents © 2005—2007 Luke Matthew Sutton