Size container queries can detect landscape / portrait orientation
- Published at
- Updated at
- Reading time
- 1min
I'm still wrapping my head around container size queries. The concept is clear (I think), but now that they're there, I'm finally catching up.
105 | 105 | 105 | 110 | 110 | 16 | 16 | 20.0 | 105 |
Manuel Matuzović discovered you can detect a container's portrait or landscape mode with Container Size Queries.
Orientation queries might be the solution to a niche problem, but I think it's exciting and makes a nice demo.
The CSS to make this work is as follows:
.container {
container-type: size;
height: 12rem;
}
@container (orientation: portrait) {
.portrait {
display: grid;
}
.landscape {
display: none;
}
}
Building this component took me surprisingly long because orientation queries have a big gotcha. If you want to evaluate a container's orientation, you must consider the inline and(!) block size and define container-type: size
. And this is where it becomes tricky for browser makers. How would you implement a container query that depends on X and Y axis with the dynamic nature of CSS? I've no idea.
So currently, you have to set an explicit height
in all major browsers (Chromium, Safari, Firefox), or your container has zero height if you want to consider both axes in your queries. Badumpts... Container queries and browsers are complicated.
In summary, this functionality makes a fancy demo, but it's hard for me to find a use case for a orienation: portrait
when I have to define the component height myself. But hey – today I learned. 😅
Join 5.5k readers and learn something new every week with Web Weekly.