Replace text with an image using CSS
Let's say you want to have a logo on a page, but you'd really like to use an <h1>
with some text for the header in the HTML. Or maybe you like to use images for all your titles, but would still like to have plain text inside header tags in your HTML.
There are a number of reasons for wanting to do this, namely accessibility and search engine optimization. I talk more about this in my post Writing Semantic HTML.
The problem is: How do you hide the text? I think the most popular technique is to wrap the text with a <span>
inside the header tag, then use some CSS to 1) hide the text, and 2) use the header tag as an image. Something like this:
<style type="text/css"> h1 { width: 500px; height: 100px; background: url(my_header_image.gif); } h1 span { display: none; } </style> <h1><span>My Great Header</span></h1>
Unfortunately, this technique makes us add an extra tag to our markup, and we all know that every time we use an unnecessary tag, a puppy dies. Either that, or we end up with ugly, unnecessarily bloated HTML.
Well here's another technique which hides the text just by using CSS. The text will still be readable by screenreaders and search engine spiders, but will disappear like magic for everyone else:
<style type="text/css"> h1 { width: 500px; height: 100px; background: url(my_header_image.gif); overflow: hidden; line-height: 500px; } </style> <h1>My Great Header</h1>
This technique works by pushing the text down inside the header with a rather large line-height (it must be at least twice the height). Then the overflow: hidden hides the text since it's overflowing.
Now isn't that better? No puppies were harmed, and we end up with slightly cleaner and shorter markup.