Reputation: 790
So I have a 300x300 square container and an <img src="" />
image inside.
What I want is the image to cover the whole container, but keep its width/height ratio.
I can easily fit the images in the container if they're all landscape or all portrait by setting the width or height to 100%
and respectively the height or width to auto
:
.container {
border: 1px solid black;
margin: 30px;
display: inline-block;
width: 300px;
height: 300px;
overflow: hidden;
}
img {
width: 100%;
height: auto;
}
<div class="container">
<img src="https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
<div class="container">
<img src="https://yada.org/wp-content/uploads/2019/05/55846576-textured-floral-dark-blue-background-abstract-vertical-background-.jpg" />
</div>
but is there any universal HTML/CSS ONLY approach to make it automatically cover the container regardless the orientation?
Note 1: The inner image should not be distorted in any way. It should only fit the container by the rules described above.
Note 2: I'm curious about an approach that doesn't imply background-image: url('')
Upvotes: 0
Views: 59
Reputation: 790
I have tried what Sitaram suggested in the comments section of the question and it seems to be the optimal solution.
Besides the fact that the images would cover the entire square, they would cover the container regardless the width or height.
Snippet:
.container {
border: 1px solid black;
margin: 30px;
display: inline-block;
width: 300px;
height: 300px;
overflow: hidden;
resize: both;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
}
<div class="container">
<img src="https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
<div class="container">
<img src="https://yada.org/wp-content/uploads/2019/05/55846576-textured-floral-dark-blue-background-abstract-vertical-background-.jpg" />
</div>
Upvotes: 0
Reputation: 529
Try this
.container {
border: 1px solid black;
margin: 30px;
display: inline-block;
width: 300px;
height: 300px;
overflow: hidden;
}
img {
width: fit-content;
min-height:300px;
}
<div class="container">
<img src="https://images.pexels.com/photos/949587/pexels-photo-949587.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
<div class="container">
<img src="https://yada.org/wp-content/uploads/2019/05/55846576-textured-floral-dark-blue-background-abstract-vertical-background-.jpg" />
</div>
Upvotes: 1