To resize an image to fit into its container, you can follow these steps:
- Use the CSS
width
andheight
properties to set the size of the container that the image will be placed in; - Set the
max-width
andmax-height
properties on the image to match the size of the container to ensure the image does not exceed the size of the container; - Use the
object-fit
property to control how the image is displayed within the container:- 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; - 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.
- Setting
For example, you can use object-fit: contain
to fit the image in the container, leaving empty space around the edges as necessary:
<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:
<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.