简体   繁体   中英

CSS responsive design - detect portrait display

I know it's with pure CSS possible to adapt the stylesheet according to screen dimensions, like this:

@media (max-width: 959px) {
  /* styles for smallest viewport widths */
}

@media (min-width: 600px) and (max-width: 959px) {
  /* styles for mid-tier viewport widths */
}

@media (min-width: 960px) {
  /* original CSS styles */
}

( source )

Is it with pure css possible to check on a landscape or portrait display?

Yes, using the following syntax:

@media all and (orientation: landscape) {}

See the w3 specs for more information.

You can use orientation :

@media all and (max-width: 959px) and (orientation : portrait) {
    /* Styles */
}

From w3 :

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

All answers are incorrect. Android will swap from portrait to landscape when the keyboard is shown.

Different keyboards also need testing as they can take up more vertical space. Swift keyboard takes up more vertical space so you cannot use solutions like @media screen and (min-aspect-ratio: 13/9) { /* landscape styles here */} as this will fail on lots of phones.

The only solution is to use javascript.

On newer Android devices you can test and use the new window.screen.orientation api.

On iOS you can use window.orientation which works fine. ie Math.abs( window.orientation ) === 90 is landscape

And as a fallback you can use window.screen.width > window.screen.height which will cover really old Android devices which don't support the new window.screen.orientation api

Then all you need to do is add / remove a class on resize / orientationchange events.

/* Android Orientation */
    var orientation = window.screen.orientation || window.screen.mozOrientation || window.screen.msOrientation || null;

    /* Check */
    if ( orientation && orientation.type ) {

        /* Landscape */
        if ( orientation.type === 'landscape' || orientation.type === 'landscape-primary' || orientation.type === 'landscape-secondary' ) {
            return 'landscape';

        /* Portrait */
        } else {                                
            return 'portrait';
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM