By now most of us are using media queries. Most of these are testing the width of the display. What if we want to target widescreen displays, or even when a user resizes their window to mimic a widescreen ratio? Enter aspect-ratio media queries.

Aspect Ratio?

Aspect ratio is the ratio between a shape’s sizes in different dimensions. In this case, that shape is either our screen, or window. We’ll get into the difference in a moment.

Aspect ratios are represented by two numbers delineated by a colon, such as 4:3. The first number represents the horizontal ratio, the second the vertical ratio.

For example, a 15″ Retina Macbook Pro has a resolution of 2880×1800. The lowest common divisor of these two numbers is 360, and dividing by that we get our 8:5 aspect ratio.

Media Queries

We have two options when it comes to querying based on aspect ratio. I’ll explain the differences in each below.

Note: Although aspect ratios are usually delineated with a colon, css uses a forward slash (/).

aspect-ratio

This media query describes the aspect ratio of the targeted display area of the output device. This means the window you are working in. If a user resizes their screen to be within the bounds of your denoted ratio, the query will go into effect.

@media screen and (min-aspect-ratio: 8/5) { ... }

In the above example, we are telling the browser to call this css is if the window aspect is 8:5 or higher. This means 8:4, 8:3, etc. will work. This will work for our Macbook example, whether the user has their browser full screen or shrinks it vertically, they will get the css.

The benefit here is we aren’t married to the aspect-ratio of the device. Since this query only takes the viewable area into account, we can get it to fire off when our user has 18 toolbars open, as it doesn’t care about the space the browser chrome is taking up.

device-aspect-ratio

This media query describes the physical aspect ration of the screen itself.

@media screen and (min-device-aspect-ratio: 8/5) { ... }

The above example will display our css when the screen aspect ratio is 8:5 or higher, regardless of how we resize our browser.

How are you using aspect-ratio media queries?

Code icon designed by Mayene de La Cruz from The Noun Project