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
<img>
elementsI'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:
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.
Images that are wide and short will be distorted in the horizontal dimension because of the hard-coded width
and min-height
rules.
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.
You can (kind of) achieve this with the CSS3 background-size
additions: contain
and cover
.
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.