Html – Changing image sizes proportionally using CSS

cssgalleryhtmllightbox

I have been trying for a couple of days now to configure my thumbnail gallery so all the images appear the same height and width. However, when I change the CSS code to,

max-height: 150px;
max-width: 200px;
width: 120px;
height: 120px;

I get images that are all the same size, but the aspect ratio is stretched, ruining the images. Is there not a way to resize the image container and not the image instead? Allowing me to keep the aspect ratio, but resize the image still. (I don’t mind if I cut off some of the image.)

Best Answer

This is a known problem with CSS resizing. Unless all images have the same proportion, you have no way to do this via CSS.

The best approach would be to have a container, and resize one of the dimensions (always the same) of the images. In my example I resized the width.

If the container has a specified dimension (in my example the width), when telling the image to have the width at 100%, it will make it the full width of the container. The auto at the height will make the image have the height proportional to the new width.

Example:

HTML:

<div class="container">
    <img src="something.png" />
</div>

<div class="container">
    <img src="something2.png" />
</div>

CSS:

.container {
    width: 200px;
    height: 120px;
}

/* Resize images */
.container img {
    width: 100%;
    height: auto;
}