According to the MDN Web Docs, “aspect-ratio” should be able to be applied to “@container”. Unfortunately I cannot reproduce it.
The context is that I want to fill an element with dynamic aspect ratio completely with an image. I explicitly do not want to use object-fit: cover; for this, as the image will be cropped and the initially invisible area can no longer be displayed later with e.g. pan and zoom. A hidden overflow is therefore desired for the parent element.
I am also open to other suggestions. Thanks in advance!
div {
overflow: hidden;
container-type: inline-size;
container-name: wrapper;
margin-bottom: 1em;
background: lightcoral;
}
.landscape {
aspect-ratio: 16/9;
width: 200px;
}
.portrait {
aspect-ratio: 9/16;
height: 200px;
}
img {
width: 100%;
height: auto;
}
@container wrapper (aspect-ratio < 1) {
img {
width: auto;
height: 100%;
}
}
<div class="landscape">
<img src="https://images.unsplash.com/photo-1722932319520-fdd0c213bf2c?q=80&w=2940&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
</div>
<div class="portrait">
<img src="https://images.unsplash.com/photo-1722932319520-fdd0c213bf2c?q=80&w=2940&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" />
</div>