Allowing wide images in flexible-width layouts

I’m a pretty ardent believer in developing web sites without tables 99% of the time. I simply feel that using tables for layout hampers your web site’s flexibility far too much to be worth it. But I have to admit: there are certain benefits to table-based layouts. One such benefit is that wide images in your layout will hold the table open.

This can lead to an ugly layout, on occasion, but it never leads to overlapping content.

Sometimes a wide image can overlap your content if you don’t plan a CSS-based layout carefully. But what if you want that wide image for a wider screen, and a narrower one for a narrower screen?
Image overlaps a CSS column
Instead we serve up a paragraph with the image in its background. The paragraph is the same height as the original image.
Image is cropped and not distorted

The existing layout occasionally makes use of wide images, and I know they want to do this from time to time. We could just leave the layout wide enough for these images, but I think it’s important that the layout flex somewhat to accommodate smaller screen sizes and/or browser windows.

Paragraphs with a background image are ok

Using CSS, there’s a fairly simple way to mitigate this problem: create a paragraph (or div) and use the image for your background. If you set a height to the paragraph based on your image’s height, then you’re good to go.

The only problem is it’s a pain to do this, and I’m not the one who will be updating the site. The site will be updated in Dreamweaver, and I want to make it as painless as possible.

Enter jQuery.

How unbelievably easy this JavaScript library seems to make things! I simply looked for any images marked up with class=”banner”, and then used jQuery to search for any such tags, grab the images’ heights & source file URIs, and then create an empty paragraph that’s the right height, with that image in the background.

Of course we have to hide the images, too. But have a look at this:
$("img.banner").each(function() { var src = $(this).attr("src"); var ht = $(this).attr("height"); $(this).replaceWith("<div style="height:"+ht+"px; background:url("+src+") no-repeat;"></div>"); });

Why, it’s almost plain readable. And few enough lines that you can swallow it. Gosh, I feel pretty darn proud of myself.

Forgetting something?

I felt pretty good about this for a few weeks, and then it hit me—users who have disabled JavaScript will see the ugly version.


Well, for them we added a tiny bit of code to the stylesheets:

img.banner { width: 100% }

This means that the image will either get squished if the client specifies a height, or shrunk if the client neglects the height, when JavaScript is turned off. Less sexy, but we get to keep the flexible layout.