Musings On Image Replacement
- By Matthew Donadio
- December 12, 2008
I normally start off my day by opening FeedDemon and marking work-related articles for later perusal. Of of the articles I read today was a new idea for a CSS image replacement. I left a comment with some thoughts about the technique, and decided to write this, too.
In the last few sites I have worked on, something hasn’t sat right when I started to implement the rules for image replacement. I typically use the Dwyer method because I think it makes the most sense from a semantic perspective (and the fact that I hate empty spans). What bothered me was the fact that I had to add document markup to accomplish this.
If we as standards-bearing web developers are promoting separation of content from presentation, then why are we adding mostly-meaningless markup to our documents? Adding empty or extra spans to a document for the sole purpose of swapping in a image seems to go against the efforts we make to avoid div-itis and class-itis.
A List Apart has had a few articles (1,2,3) about progressive enhancement with regards to web design (as opposed to graceful degradation). This has gotten me thinking again about image replacement.
In my mind, there are five basic levels when it comes to progressive enhancement with a website.
- Text-only
- Text+images
- Text+images+CSS
- Text+images+CSS+JavaScript
- Text+images+CSS+JavaScript+Flash
Given the prevalence and popularity of ajax-enabled and other sites that require javascript, then maybe using JS for image replacement isn’t a bad idea. Besides, with this ideology, JS isn’t a requirement for the site, it just enhances the visual appearance. There are also several mature libraries that make implementation much easier. With jQuery, it is pretty simple to add in a class name onto the element you want to replace, alter the content as needed for your preferred method, and then reuse your CSS rules for image replacement.
For example, let’s assume that we have the following in our CSS:
.replace span { /* dwyer image replacement */
display: block;
width: 0;
height: 0;
overflow: hidden;
}
#mydiv.replace {
width: 100px;
height: 100px;
background: url(some_image.png) left top no-repeat;
}
We can then simply add
$("#mydiv").addClass("replace").wrapInner("<span></span>");
to perform the image replacement.
I haven’t totally thought this through yet, but I would love to hear what others think. I put together a small example that demonstrates this.