I want to apply different CSS styles depending on whether the orientation of the device is vertical (portrait mode ) or horizontal (landscape mode ) . Can it be achieved with just CSS?
Is there an alternative? I suppose 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 an easier way that uses only CSS (if not, a JS solution would be nice).
Theoretically it is possible only with css, I mean theoretical because I have never tried it:
Some documentation on w3 and MDN .
According to the w3 specification:
There is a rather interesting note in the MDN documentation:
Some alternatives:
In CSS3 it exists in
media
the optionorientation
Example
At the moment the best way to do it in Javascript is through the API
window.matchMedia()
(doc) since it has optimal compatibility with browsers. Still, in the case of using a new or unconventional browser, it's not bad to add a conditionelse
that offers a workaround like the one I recommend below.By comparing the height and width of the device, its orientation can be determined based on the highest value, the disadvantage of this method is that it can fail if the device's keyboard is displayed, since some browsers subtract the space that the keyboard occupies from these values altering the result. But if the check is done at page load time this problem does not persist, so this seems to be an excellent option B.
Code:
In javascript you can do: