Polizi8
Polizi8

Reputation: 275

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?

Upvotes: 6

Views: 6619

Answers (4)

Elyes Chtioui
Elyes Chtioui

Reputation: 1

You can use the min-resolution media feature to target devices with a high pixel density screens (i.e. most modern mobile devices) and the orientation media feature to target those devices in landscape mode.

@media screen and (orientation: landscape) and (min-resolution: 240dpi) {
   /* CSS rules for mobile devices in landscape orientation go here */
}

Upvotes: 0

Johannes
Johannes

Reputation: 67799

There is a query @media pointer, which determines whether the the user has a pointing device (like a mouse). Since mobile devices don't have a pointer, you could combine not: pointer and orientation: landscape, like this

 @media (not: pointer) and (orientation: landscape) { ... }

Upvotes: 2

Albenis Kërqeli
Albenis Kërqeli

Reputation: 130

Try this:

    @media (orientation: landscape) {    

}

Upvotes: -2

Alessio
Alessio

Reputation: 3626

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.

Upvotes: 20

Related Questions