user1544337
user1544337

Reputation:

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?

Upvotes: 9

Views: 26044

Answers (4)

Matt
Matt

Reputation: 81

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';
        }

    }

Upvotes: 0

Eli
Eli

Reputation: 14827

You can use orientation:

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

Upvotes: 3

Vucko
Vucko

Reputation: 20834

From w3:

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

Upvotes: 2

mogelbrod
mogelbrod

Reputation: 2306

Yes, using the following syntax:

@media all and (orientation: landscape) {}

See the w3 specs for more information.

Upvotes: 15

Related Questions