tommarshall
tommarshall

Reputation: 2128

CSS media query orientation and portrait device-width logic

I have two divs, which I'll refer to as A & B. The desired behaviour is:

  1. If the screen width is less than 400px, only A should be visible.
  2. If the screen in landscape, greater than 400px in width, but less than 400px in portrait orientation, only B should be visible.
  3. Else (the screen width is greater than 400px in both portrait and landscape), both A and B should be visible.

The second item is the one that's proving to be problematic.

My current approach is working for iOS devices, which always report min-device-width & max-device-width as the portrait values regardless of the current screen orientation, but not for android and others, where the device-width values change with the orientation:

/* item 3 */
.a, .b {
  display: block;
}

/* item 2 */
@media only screen and (min-width: 400px) and (max-device-width: 400px) and (orientation: landscape) {
  .a { display: none; }
}

/* item 1 */
@media only screen and (max-width: 400px) {
  .b { display: none }
}

Is it possible to implement this behaviour purely in media queries so that it works on all devices?

I'm keen to avoid JavaScript, UA Sniffing, and the use of the deprecated media types (e.g. handheld) if possible.

Upvotes: 1

Views: 6124

Answers (1)

tommarshall
tommarshall

Reputation: 2128

One solution is to add a second media query for item 2, that targets the max-device-height:

/* item 2a - iOS */
@media only screen and (min-width: 400px) and (max-device-width: 400px) {
  .a { display: none; }
}
/* item 2b - everything else */
@media only screen and (min-width: 400px) and (max-device-height: 400px) {
  .a { display: none; }
}

2a targets the iOS devices that always report min-device-width & max-device-width as the portrait values regardless of the current screen orientation.

2b targets every other device that reports min-device-width & max-device-width based on the current screen orientation. So if the screen orientation is landscape, then the max-device-height represents the portrait orientation screen width.

These media queries can also be combined with a ,:

/* item 2 */
@media only screen and (min-width: 400px) and (max-device-width: 400px) and (orientation: landscape), only screen and (min-width: 400px) and (max-device-hieght: 400px) and (orientation: landscape) {
  .a { display: none; }
}

Upvotes: 4

Related Questions