To resize an image to fit into its container, you can follow these steps:
- Use the CSS
widthandheightproperties to set the size of the container that the image will be placed in; - Set the
max-widthandmax-heightproperties 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-fitproperty to control how the image is displayed within the container:- Setting
object-fit: containwill ensure that the entire image is visible within the container, even if it means leaving empty space around the edges; - Setting
object-fit: coverwill 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.