I am trying to find a solution without having to use background-image
, but being able to use an inline <img>
.
I would like to make it so that if the image container's dimensions are not the same as the image, the image will still fill the width and height of the container, cropping whatever part it has to.
Also, if a part of the image is smaller than the container, it will stretch over 100% to fill the container.
In the example below, I have a huge image that can easily fill the width and height of the container. The container is a different aspect ratio from the image, so I end up with blank space, either horizontally or vertically. I want to fill that container no matter what, even though part of the image will be cropped away.
class[*='container'] {
margin-bottom: 50px;
}
.container img {
width: 20%;
height: 20%;
}
.container-1 {
background: #f0f0f0;
width: 400px;
height: 150px;
}
.container-1 img {
object-fit: cover;
max-width: 100%;
max-height: 100%;
}
.container-2 {
background: #f0f0f0;
width: 150px;
height: 400px;
}
.container-2 img {
object-fit: cover;
max-width: 100%;
max-height: 100%;
}
<p>Original image:</p>
<div class="container">
<img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>
<p>Container 1:</p>
<div class="container-1">
<img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>
<p>Container 2:</p>
<div class="container-2">
<img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>