Search code examples
cssmedia-queriesaspect-ratio

How do i use two aspect-ratios in a media query?


Im trying to set a behaviour for different screen sizes, e.g. I want to have a set of css rules for any screen between the aspect ratio 320x560 and the aspect ratio 414x736.

I've already tried taking a similar approach as one might do if working with min-width and max-width.

Everything is on here: codepen There you can see that i have a working example for widths commented out, but for some reason it won't work with aspect ratio.

@media (min-aspect-ratio: 600px/495px) and (max-aspect-ratio: 1000px/800px){
    div {
    color: yellow;
    }
}

Solution

  • Firefox only works at the exact ratios for me.

    A ratio is not a value on its own, rather, its the result of a computation. I don't believe any CSS engine is designed to compute the current aspect ratio and compare it between two potential values, it only works with the currently computed ratio. You would be able to accomplish this in javascript if you applied a listener to the window resize event.

    To do it in CSS you would need to create multiple media queries that define a min-height, max-height, min-width, max-width along with a single ratio to create a range.

    Interesting question though, never thought to try a aspect ratio range before. Would be useful to implement.