Pure CSS image thumbnails

Will McCutchen picture Will McCutchen · May 25, 2011 · Viewed 36.4k times · Source

I want to display a collection of image thumbnails in a grid. The images will come in a variety of sizes, but I'd like to restrict the thumbnails to a particular size (let's say 200px wide and 150px tall).

What I'd like to find are some magical HTML markup and CSS rules that will

  1. Allow the images to be included in normal <img> elements
  2. Ensure that the thumbnails fit into their 200x150 pixel box, retain their proportions, and are centered in whichever dimension they overflow.
  3. Not require JavaScript or specific knowledge of each image's actual dimensions

I'm not sure if this is possible. I can make a (bad) approximation of what I want with the following markup:

<div class="thumb">
    <img src="360x450.jpeg">
</div>

and CSS:

.thumb {
    width: 200px;
    height: 150px;
    overflow: hidden;
}
.thumb img {
    min-width: 200px;
    min-height: 150px;
    width: 200px;
}

This attempt breaks in a variety of ways:

  1. Images that are in portrait orientation will be sized correctly, but will overflow through the bottom of the container, resulting in vertically-off-center cropping.

  2. Images that are wide and short will be distorted in the horizontal dimension because of the hard-coded width and min-height rules.

  3. But without that hard-coded width, images that are larger than the minimum height and width will not be resized at all.

If it's at all helpful, I've put up an example that will (hopefully) illustrate what I'm trying to do, here:

I know that I can solve this problem by omitting the <img> element altogether and instead pulling the thumbnails in as a centered background image on the containing element, but, if it's possible, I'd like to keep the <img> elements in the page.

Thanks for any help or pointers you can provide!

Edit: I suppose I should note that an ideal solution will work in IE 6+ and modern browsers, but any solution that works in IE 9+ and other modern browsers (recent WebKit, Gecko, etc.) will be gladly accepted.

Answer

drudge picture drudge · May 26, 2011

You can (kind of) achieve this with the CSS3 background-size additions: contain and cover.

Live Demo

  • contain (top picture) fits the entire image, keeping aspect ratio. Nothing is cropped.

  • cover (bottom picture) fills the containing element either vertically or horizontally (depending on the image) and crops the rest.