Accessible image replacement with CSS3
Image replacement is as old as CSS tips and tricks posted online. Here’s a list of available techniques. Recently I’ve become particularly interested in the Gilder/Levin method. It uses additional span element, positioned over the parent. This span then gets background-image treatment, covering underlying text.
I normally use it like this:
<h1>Futurama <span></span></h1>
h1 {
position: relative;
width: 256px;
height: 133px;
}
h1 span {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url("image.png") no-repeat;
}
Why do I bother? This is the only (sane) method allowing images to be disabled or not downloaded at all. And why would I care about this?
- I want to provide alternative way to access all content on the page, full stop. This is supposed to be a replacement, not obliteration.
- There is a small lag between rendering DOM element and downloading the image. Browsers are so fast these days that it can happen even on broadband.
It’s all good and I use it all the time for logo elements (headings usually get @font-face anyway). The only thing that bugs me is that additional span element. Today I learned how to get rid of it.
Note: In my daily work I support only modern browsers (including IE8), so if you need to support earlier versions of Firefox (3.0) or IE 4.0, stop reading. ;)
Code looks like this:
<h1>Futurama</h1>
h1 {
position: relative;
width: 256px;
height: 133px;
}
h1:after {
content: url("image.png");
position: absolute;
left: 0;
top: 0;
}
Test it here, works like a charm. I used content: url() by purpose – there is a strange bug that won’t allow text to be covered in IE8 just by using background-image. Image must have the same dimensions as parent element or you must clip it adding overflow: hidden to h1.
If you have any comments and/or improvements, get in touch.
PS: “CSS3” in the title refers to the ability to position generated content (which was indeed introduced in CSS2). Don’t send angry emails. :)












