In this guide you can learn a technique for causing an HTML image to completely fill a box.
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 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.
<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>.wrapper {
height: 200px;
display: flex;
gap: 20px;
}
.box {
border: 5px solid black;
}
.box img {
width: 100%;
height: 100%;
}
.box1 img {
object-fit: cover;
}
.box2 img {
object-fit: contain;
}
.box3 img {
object-fit: fill;
}