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>
Edit: Image for clarification
2
Answers
The
aspect-ratio
condition in @container queries doesn’t seem tobe implemented yet by most navigators, regarding
Can I use?‘s entry about container queries.
But you’ve already got the
portrait
andlandscape
classes, soyou can probably do different rules without querying the aspect-ratio,
especially as it is fixed by yourself.
But you can still do queries on the width and then decide what to do.
Just keep in mind that if you want to switch automatically between
portrait and landscape, depending on the space available (width of the
container), then I think you’ll have to add an inner div which contains
the image and your other tools to zoom and pan.
Here’s a way to make your image use the height:
Notice that I replaced your
div
selector by.image-box
sothat it can’t break other divs used for other purpose.
I didn’t think about the centred vertical alignment of the image
in the landscape mode. We perhaps have to also use transforms
or other CSS techniques.
I’m not sure why you don’t want
object-fit:cover
? Based on your description it sounds like the ideal solution. Here I have made the image container resizable so you can see how it behaves at any aspect ratio. By default the images would be centred but I have addedobject-position: left top;
to match your illustration.But to answer your question about container queries: Use
container-type: size;
instead ofcontainer-type: inline-size;
. inline-size refers to just the width whereas size considers both width and height (and both are needed to calc aspect-ratio).