Flexible Width Images for Elastic Layouts
Nettuts recently posted an interesting technique for creating “flexing images”. Essentially, CSS is used to crop the image so that the width adjusts to fit the browser without any scaling or stretching. This technique solves a common problem with elastic layouts: an image that is surrounded by empty space on a large monitor may still break the layout on smaller screens.
The Nettuts method — placing the image in the background of a div — works, but with a few issues. An empty div is required which produces extra markup with no semantic meaning to the document. And by using a background image, there is no alt text for accessibility. The method is also hard to maintain as each image requires it’s own CSS class.
Fortunately, Brandon Eley posted a comment showing his solution which addresses all of these concerns. I’ve made a few small changes myself and posted the code below with instructions on how to implement it. It’s compatible with IE (5.5, 6, and 7) as well as Firefox, Safari, and likely most other browsers as well.
View the demo page to see the end result.
How to implement it
To try this out you’ll need an image that is wide enough to fit the largest monitor you want to support (I chose 1200 pixels) and preferably has the subject in the centre.
Place the following code where you want to display the image:
<div id="image"> <img src="image.jpg" alt="Modern building at night"> </div>
Now add this to your stylesheet:
/* Div containing the image */
#image
{
width: 80%;
margin: auto; /* Center the div */
overflow: hidden; /* Hide part of image that doesn't fit */
text-align: center; /* Center image. Omit to crop right */
}
/* The image itself */
#image img {
margin: 0 -600px; /* Set to half of the image's width for
even cropping (-600px). Or use a larger value (-100px)
to limit the amount of cropping on the left-hand. */
}
That’s it! Compare your results with the demo page to confirm it worked.
A few drawbacks
Although this method could be very useful, there are a few downsides that should be mentioned:
- Users will download the full-size image, even if they only see a portion of it. Compress where possible and don’t get carried away with using an excessively large image.
- Some images (like group portraits) may not show the whole subject when cropped. Try to select images with the subject at the centre and plenty of empty space at the sides.
- Although quite simple, there is still some additional HTML and CSS to deal with.
Conclusion
It’s not perfect, but this could be a very useful technique under the right circumstances. I’d be interested to hear some thoughts on this method — as well as flexible images in general — and any suggestions for improvements to the code. If you do use it, post up a link so we can have a look!
Have something to add? Leave a comment.