aspect-ratio
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The aspect-ratio
CSS media feature can be used to test the aspect ratio of the viewport.
Syntax
Examples
In the example below, a Note that, when none of the media query conditions are true, the background will turn white because none of the below rules will be applied to the Note the From the initial state, as you reduce height, the aspect ratio starts increasing from one. So the div's background color goes from red(1) < green(1.5) < white < blue(1.6).. The iframe creates its own viewport. Resize the
to see
aspect-ratio
in action.
. See if you can find which width and height values trigger this!
HTML
CSS
/* Minimum allowed aspect ratio */
/* Select aspect ratios 8/5 = 1.6 and above */
@media (min-aspect-ratio: 8/5) {
div {
background: #99f; /* blue */
}
}
/* Maximum allowed aspect ratio */
/* Select aspect ratios 3/2 = 1.5 and below */
@media (max-aspect-ratio: 3/2) {
div {
background: #9f9; /* green */
}
}
/* Exact aspect ratio, put it at the bottom to avoid override */
@media (aspect-ratio: 1/1) {
div {
background: #f99; /* red */
}
}
Result
min-aspect-ratio: 8/5
sets the lower bound to 1.6, so this media query selects elements with aspect ratios 1.6 and above. The max-aspect-ratio: 3/2
sets the upper bound, so this media query selects elements with aspect ratios 1.5 and below. The aspect-ratio: 1/1
overrides the max aspect ratio rule because it has been declared after and selects elements with aspect ratios exactly 1
.Specifications
Specification Media Queries Level 4
# aspect-ratioBrowser compatibility
See also