How to Make an Image Fit Into Its Container Using CSS?

To resize an image to fit into its container, you can follow these steps:

  1. Use the CSS width and height properties to set the size of the container that the image will be placed in;
  2. Set the max-width and max-height properties on the image to match the size of the container to ensure the image does not exceed the size of the container;
  3. Use the object-fit property to control how the image is displayed within the container:
    1. Setting object-fit: contain will ensure that the entire image is visible within the container, even if it means leaving empty space around the edges;
    2. Setting object-fit: cover will ensure that the container is completely filled with the image, even if it means part of the image is cropped.

For example, you can use object-fit: contain to fit the image in the container, leaving empty space around the edges as necessary:

Example Image of Plumeria
<div class="container">
  <img src="https://static.designcise.com/img/examples/plumeria.jpg" />
</div>
.container {
  width: 200px;
  height: 200px;
  border: 1px solid red;
}

.container > img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

Similarly, you can use object-fit: cover to completely fill the container with the image, cropping parts of it as necessary:

Example Image of Plumeria
<div class="container">
  <img src="https://static.designcise.com/img/examples/plumeria.jpg" />
</div>
.container {
  width: 300px;
  height: 100px;
  border: 1px solid red;
}

.container > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.