如何使用 CSS 媒体查询检测设备方向?

问题描述 投票:0回答:7

在 JavaScript 中,可以使用以下方式检测方向模式:

if (window.innerHeight > window.innerWidth) {
    portrait = true;
} else {
    portrait = false;
}

但是,有没有一种方法可以仅使用 CSS 来检测方向?

例如。像这样的东西:

@media only screen and (width > height) { ... }
browser css tablet media-queries
7个回答
537
投票

CSS 检测屏幕方向:

 @media screen and (orientation:portrait) { … }
 @media screen and (orientation:landscape) { … }

媒体查询的 CSS 定义位于 http://www.w3.org/TR/css3-mediaqueries/#orientation


40
投票
@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */
}

但看起来你仍然需要实验


32
投票

我认为我们需要编写更具体的媒体查询。确保如果您编写一个媒体查询,它不应该影响其他视图(Mob、Tab、Desk),否则可能会带来麻烦。我想建议为相应的设备编写一个基本媒体查询,其中涵盖视图和一个方向媒体查询,您可以针对方向视图具体编写更多代码,以获得良好的实践。我们不需要同时编写两个媒体方向查询。你可以参考我下面的例子。如果我的英语写作不太好,我很抱歉。 例如:

手机版

@media screen and (max-width:767px) {

..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.

}


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {


..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

平板电脑

@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query  CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.

}

桌面

根据您的设计要求享受...(:

谢谢, 极土


13
投票

我会选择纵横比,它提供了更多的可能性。

/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
    ...
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    ...
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
    ...
}

方向和纵横比都取决于视口的实际大小,与设备方向本身无关。

了解更多:https://dev.to/ananyaneogi/useful-css-media-query-features-o7f


4
投票

orientation
似乎没有按预期工作。
aspect-ratio
合作可能是更好的方法。

@media only screen and (max-aspect-ratio: 1/1){
//portrait
}
@media only screen and (min-aspect-ratio: 1/1){
//horizontal
}

1
投票

在 Javascript 中,最好使用

screen.width
screen.height
。这两个值在所有现代浏览器中都可用。它们给出了屏幕的真实尺寸,即使应用程序启动时浏览器已缩小。
window.innerWidth
当浏览器缩小时会发生变化,这在移动设备上不会发生,但可能会在 PC 和笔记本电脑上发生。

screen.width
screen.height
的值会随着移动设备在纵向和横向模式之间切换而变化,因此可以通过比较值来确定模式。如果
screen.width
大于 1280 像素,则您正在使用 PC 或笔记本电脑。

您可以在 Javascript 中构造一个事件监听器来检测两个值何时翻转。需要关注的纵向 screen.width 值为 320px(主要是 iPhone)、360px(大多数其他手机)、768px(小型平板电脑)和 800px(普通平板电脑)。


0
投票

我们可以使用下面的代码进行测试

@media all and (orientation:portrait) {
 // simple css for portrait mode of mobile device
}

@media all and (orientation:landscape) {
 // css for landscape mode
}

更多信息:https://www.w3.org/TR/mediaqueries-3/#orientation

© www.soinside.com 2019 - 2024. All rights reserved.