I have to display a bunch of images in a page. Images are of different size, some very wide and some very thin. I want to put them all in a container of fixed width and fixed height.
The logic of placing the images should be like this: Say if image is smaller than the container, scale it up to the maximum size such that the aspect ratio is maintained, and put it at the center of container. If image is bigger, scale it down while maintaining the aspect ratio.
Some examples: Say our container is 150x150, and we have an image sized 100x50. In this case the image should be scaled up to 150x75. If we have an image sized 100x300, the image should be scaled down to 50x150.
While this can be easily done with javascript, I'd like to avoid that if possible. I'm wondering if there's any way to accomplish this with CSS alone. I can live with a CSS3 only solution, or even with webkit/firefox specific directives, as long as it works on latest versions of Chrome, Firefox and Safari (I will use a fallback for IE if there's no choice).
Edit: I know about max-height and max-width of course. The issue is that if I set both max-height and max-width to 150, images won't be scaled up if needed.
Don't use an
<img>
. Instead, use abackground-image
style:The
background-size
does the magic, scaling the image up or down so that it snugly fits inside the container.Check out this fiddle http://jsfiddle.net/demchak_alex/FazvX/3/
Though this only works if you can apply classes to individual images
EDIT:
if you can use background images, check out this fiddle http://jsfiddle.net/demchak_alex/FazvX/4/
The "image only with added classes" works on the top, and the using background images works on the bottom.