@media query device - how to portrait one css, landscape other?

10,766

You can do this by using the css media feature "orientation". This way you can specify styles depending on screen orientation, unrelated from screen size. You can find the official w3.org definition about this media feature here. Combined with the specifications on developer.mozilla.org this will explain how it works.


Quote from w3.org about the ‘orientation’ media feature:

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’.

A note/quote from developer.mozilla.org about the "orientation" feature:

Note: This value (ie portrait or landscape) does not correspond to actual device orientation. Opening the soft keyboard on most devices in portrait orientation will cause the viewport to become wider than it is tall, thereby causing the browser to use landscape styles instead of portrait.


So to recapitulate, it is not actually the screen orientation that triggers portrait or landscape media queries. However it is the ratio between height and width of the screen! Because of this it also makes sense to use the "orientation feature" with non mobile/tactile devices hence I've added a small demo to show the behaviour of these media queries.

JSFIDDLE DEMO (try resizing the view port)

Here are the representative media queries affecting portrait and landscape orientation.

 @media screen and (orientation:portrait) {
     /* Portrait styles */
     /*hide your main content and display message */

 }
 @media screen and (orientation:landscape) {
     /* Landscape styles */
     /* show your content*/

 }
Share:
10,766
Münter
Author by

Münter

Updated on June 05, 2022

Comments

  • Münter
    Münter almost 2 years

    How can I add two different @media query css stylesheets for a device.

    So that when you have it in portrait it actives one And when in landscape it activates another.


    My case:

    I am trying to create a page that only works in landscape (1024px), so when you have your device (In my case Ipad) in portrait (768px) it activates a css that tells you to turn your screen sideways/landscape.

    I tried this:

    <link rel="stylesheet" media="@media only screen and (max-device-width : 1024px) and (orientation : landscape)" href="css/tabphone.css" />
    <link rel="stylesheet" media="@media only screen and (max-device-width : 768px) and (orientation : portrait)" href="css/turn.css" />
    

    But then it only activates the last one of them.

    Anybody know a way to solve my problem :-) ?

  • Münter
    Münter over 10 years
    but won't this affect my site when viewed on a pc?
  • Münter
    Münter over 10 years
    Ah brilliant! put it in both the css's and it works! Thanks you so much :-)
  • kasper Taeymans
    kasper Taeymans over 10 years
    added a jsfiddle demo