I have a square container with dimensions of 300x300 and an <img src="" />
image inside.
My goal is for the image to cover the entire container while maintaining its width/height ratio.
- If the image's width is smaller than its height (portrait), it should have 100% width with some height cropped.
- If the height is smaller than the width (landscape), it should have 100% height with excess width cropped.
I can easily accommodate images in the container if they are all landscape or all portrait by adjusting the width or height to 100%
and setting the other dimension 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>
However, I am looking for a universal HTML/CSS ONLY solution that will automatically fit the image to cover the container regardless of its orientation.
Note 1: The inner image must not be distorted in any way. It should only fit the container based on the rules mentioned above.
Note 2: I am interested in an approach that does not involve using background-image: url('')