cssmobilemedia-querieslandscapeportrait

How to target only landscape mobile devices without affecting desktop via CSS?


Is there a simple way to target landscape mobile devices without affecting desktop ones, without entering the screen size for every device?
If not, is there a single best resolution to target most of the users?
Nowadays mobile screens can have a resolution equal or grater than most desktop screens, I can't see why many use rules for resolutions below 640x480.

For example, to target portrait devices (99% are mobile), one could write his rules in

/*Global and desktop rules*/

@media only screen and (orientation: portrait) {
/*Mobile overwrites*/
}

However, the same query for orientation: landscape would affect desktop users as well.
My temporary workaround is to use vw, vh and vmin, but I would like to know if there's a better way.

Would a mobile CSS media simplify web developers' job?


Solution

  • You can mix CSS Media Queries for orientation to detect landscape mode and hover + pointer to detect a touch device.

    @media (orientation: landscape) and (hover: none) and (pointer: coarse) {
    /* your CSS to target only landscape mobile users */
    }
    

    For a reference to detect a touch device with only CSS here's a good article on medium.

    The best solution is to use JavaScript to detect the device and add a class to the <body> or the <html> in order to add your CSS. You can have a look at current-device, you just include the script, that then updates the <html> section with the appropriate classes based on the device's characteristics.

    Hope this helps.