CSS Reference ยท Media Queries and Features
The aspect-ratio media feature
Reference for the aspect-ratio media feature: query the viewport width-to-height ratio, use min- and max- forms or ranges, and avoid confusing it with the property.
The aspect-ratio media feature compares the viewport's width to its height. A 1280 by 720 window has a ratio of 16/9; a phone held upright might be about 9/19. It is a different thing from the aspect-ratio property, which sizes a box; here you are testing the shape of the screen.
@media (aspect-ratio >= 16/9) { .hero { height: 100vh; } }
Try it
The panel changes as the preview's shape moves across a ratio of 2 to 1. Resize your window to see it flip.
Syntax
@media (aspect-ratio: 16/9) { /* exactly 16:9 */ } @media (min-aspect-ratio: 4/3) { /* at least 4:3 */ } @media (max-aspect-ratio: 1/1) { /* square or taller */ } @media (aspect-ratio >= 2/1) { /* range syntax */ }
It is a range media feature.
Values
| Value | Description |
|---|---|
<number>/<number> |
The ratio of width to height, such as 16/9. |
<number> |
A single number is the same as dividing by 1, so 2 means 2/1. |
Usage notes
- Exact matches are fragile. Windows rarely have a precise ratio like
16/9. Usemin-,max-or>=and<=comparisons. - Ratio is not size. Two screens with the same ratio can differ hugely in pixels. Combine with a
widthtest when absolute size matters. - A simpler alternative. If you only care about portrait versus landscape,
orientationis easier to read. - It is about the viewport. The ratio can change at any moment while the user resizes the window or rotates the device.
- Container queries. For components, a container query on
aspect-ratiomeasures the container instead of the viewport (see container features). - Write the ratio with a slash.
4/3and4 / 3are both valid, but4:3is not.
Browser support
Supported in every browser for the min- and max- forms; the range syntax needs a current browser, so check a compatibility table if you support older versions.
Related
aspect-ratioproperty โ sizes a boxorientationโ portrait or landscape@mediaโ the at-rule- Lesson: Media Queries