Container Orientation Query — Portrait vs Landscape
Use the orientation container feature to apply different styles when a container is taller than wide (portrait) or wider than tall (landscape).
Detailed Explanation
Container Orientation Queries
The orientation feature in container queries works similarly to the viewport orientation media feature but applies to the container's dimensions instead.
The CSS
.panel {
container-type: size; /* Must be 'size' for orientation */
container-name: panel;
width: 100%;
height: 400px; /* Explicit height required for size containment */
}
@container panel (orientation: landscape) {
.panel-layout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
}
}
@container panel (orientation: portrait) {
.panel-layout {
display: flex;
flex-direction: column;
gap: 1rem;
}
}
How Orientation Is Determined
- Landscape: Container width >= container height
- Portrait: Container height > container width
Requirements
Since orientation depends on both width and height, you must use container-type: size (not inline-size). The container must have a deterministic height.
Practical Example: Image Gallery
.gallery-container {
container: gallery / size;
width: 100%;
height: 100%;
}
@container gallery (orientation: landscape) {
.gallery {
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(2, 1fr);
}
}
@container gallery (orientation: portrait) {
.gallery {
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(4, 1fr);
}
}
The gallery uses more columns in landscape orientation and more rows in portrait, adapting naturally to the container's shape.
Use Case
Use orientation container queries for panels, modals, or embedded widgets where the container's aspect ratio determines the best layout direction. Requires container-type: size with an explicit height.