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.
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.
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.
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.