How to fill a box with an image without distorting it
In this guide you can learn a technique for causing an HTML image to completely fill a box.
Using object-fit
When you add an image to a page using the HTML <img>
element, the image will maintain the size and aspect ratio of the image file, or that of any HTML width
or height
attributes. Sometimes you would like the image to completely fill the box that you have placed it in. In that case you first need to decide what happens if the image is the wrong aspect ratio for the container.
- The image should completely fill the box, retaining aspect ratio, and cropping any excess on the side that is too big to fit.
- The image should fit inside the box, with the background showing through as bars on the too-small side.
- The image should fill the box and stretch, which may mean it displays at the wrong aspect ratio.
The object-fit
property makes each of these approaches possible. In the example below you can see how different values of object-fit
work when using the same image. Select the approach that works best for your design.
html
<div class="wrapper">
<div class="box box1">
<img
alt="a colorful hot air balloon against a clear sky"
src="https://mdn.github.io/shared-assets/images/examples/balloon.jpg" />
</div>
<div class="box box2">
<img
alt="a colorful hot air balloon against a clear sky"
src="https://mdn.github.io/shared-assets/images/examples/balloon.jpg" />
</div>
<div class="box box3">
<img
alt="a colorful hot air balloon against a clear sky"
src="https://mdn.github.io/shared-assets/images/examples/balloon.jpg" />
</div>
</div>
css
.wrapper {
height: 200px;
display: flex;
gap: 20px;
}
.box {
border: 5px solid #000;
}
.box img {
width: 100%;
height: 100%;
}
.box1 img {
object-fit: cover;
}
.box2 img {
object-fit: contain;
}
.box3 img {
object-fit: fill;
}