Skip to main content
Coderweekend

How to scale Heigh to match max-width in CSS

It is a good practice to include width and height attributes to your images to prevent layout shift problems.

But in a responsive web design where the container can shrink, the problem arises.

As you can see, an image will overflow when the screen width is limited.


A problem of fix width in responsive web design.
A problem of fix width in responsive web design.

Prevent an image from overflowing its container #

To prevent this, we can use max-width in CSS.

img {
max-width: 100%;
}

The image now fits within its container but is stretched out vertically. The image height is not scaled to match the width.


max-width: 100%
max-width: 100%

We can fix this with another property, object-fit.

img {
max-width: 100%;
object-fit: contain;
}

By using object-fit: contain;, we make an image scale to fit within the container and keep its aspect ratio.

But another problem arises, even if the image is scaled correctly, it still occupied the original height.

As a result, you will see a blank space on the top and bottom of the image.


object-fit: contain
object-fit: contain

How to scale a height to match a max-width in CSS #

The solution for this problem is to use a combination of two properties, max-width and height.

img {
max-width: 100%;
height: auto;
}

Set the height of the element to auto using the height property will allow the height of the element to adjust proportionally to the width, maintaining the aspect ratio of the image.

You no longer need object-fit: contain; with this approach.


height: auto
height: auto