To auto-resize an image to fit into a div container using CSS, you can use the ‘object-fit’ property.

.container img {
    object-fit: cover;
}

This will make the image cover the entire div container while preserving its aspect ratio. The image will be resized to fill the container without cropping any part of it.

Here is an example:

HTML:

<div class="container">
    <img src="image.jpg" alt="image">
</div>

CSS:

.container {
    width: 300px;
    height: 200px;
}
.container img {
    object-fit: cover;
    width: 100%;
    height: 100%;
}

Alternatively, you can also use object-fit: contain which will make the image fit inside the container while preserving its aspect ratio, so the whole image will be visible but it might not fill the entire container.

Another option would be to use background-size property on the container.

.container {
    width: 300px;
    height: 200px;
    background-image: url(image.jpg);
    background-size: contain;
    background-repeat: no-repeat;
}

This method will make the container auto-resize the image to fit it and also you can set the position of the image inside the container using ‘background-position’ property.

Also Read:

Categorized in: