javascript – Detect if the orientation is portrait or landscape

Question:

I want to apply different CSS styles depending on whether the device orientation is vertical (portrait or portrait mode) or horizontal (landscape or landscape mode). Can it be achieved with just CSS?

Is there an alternative? I suppose that you could always detect the width and height of the window with JavaScript and from there decide which styles to apply, but I wonder if there is some simpler way that uses only CSS (if not, a solution with JS would be fine).

Answer:

Theoretically possible only with css, I mean theoretical because I have never tried:

@media all and (orientation: portrait) { ... }

@media all and (orientation: landscape) { ... }

Some documentation on w3 and MDN .

According to the specification of w3:

The orientation is portrait when the height value of the viewport is greater than or equal to the width value, otherwise the orientation will be landscape .

There is a rather interesting note in the MDN documentation:

Keep in mind that when the keyboard is displayed on a mobile device in portrait mode, the viewport may be wider than it is high, so the browser can use the landscape styles at that time, and not the portrait styles.


Some alternatives:

Scroll to Top