Search code examples
cssmedia-queries

How can I detect which window dimension is bigger just using CSS media query?


Does anybody know how to create a media query that would behave like this:

@media screen and (width greater than height){}

or

@media screen and (height less than width){}

For what is stated in the syntax specification it's not possible to use 'media_feature' as values. Is there any workaround WITHOUT using JavaScript? The closest thing I could get was using aspect-ratio but it was not functional.

Thanks.


Solution

  • You can use an orientation media query:

    @media all and (orientation:portrait) { … }
    @media all and (orientation:landscape) { … }
    

    From the W3C media Queries spec:

    The ‘orientation’ media feature is ‘portrait’ when the value of the ‘height’ media feature is greater than or equal to the value of the ‘width’ media feature. Otherwise ‘orientation’ is ‘landscape’.

    But note that it usually make more sense to worry about the actual width than the orientation, see this article on QuirksBlog for details.