在样式文件中使用media query时,device-height的取值问题
发布于 5 年前 作者 juanlong 12096 次浏览 来自 问答

需要使用media query作个别设备的适配时。例如对于iPhone X,设备的高度(css px单位)为812

通常在前端开发时,这样写就可以


[@media](/user/media) screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {


}


但在小程序开发时,在*.wxss中按上述写法,在真机上可以work,在工具上不work

如果把上述代码中的device-height: 812px 改为 device-height: 724px,这时工具上反而可以work,真机则不work

因为724px是从小程序的标题栏下边缘开始到屏幕底部的长度,也就是viewport的高度

猜测这里是不是小程序开发工具的media-query的device-height的取值实现有问题。

(代码片段中有两个方形,两个方形各自使用device-height为812px和724px赋予了一段样式。如果这个bug存在,那么预期结果是:真机(iPhone X手机)上,左边的方形出现红色下划线;开发者工具(选择模拟设备为iPhone X)上,右边的方形出现红色下划线

--------------------

更新一下我们实际开发的app中遇到的情况。需要适配的是,当手机为iPhone X时,为购买按钮下方增加一些空白以留出触控条

  1. 当wxss代码为如下(device-height取812)时

[@media](/user/media) screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {


}

真机和工具的表现如下:(真机中样式生效,工具中样式不生效)

  1. 当wxss代码为如下(device-height取724)时

[@media](/user/media) screen and (device-width: 375px) and (device-height: 724px) and (-webkit-device-pixel-ratio: 3) {


}

真机和工具的表现如下:(真机中样式不生效,工具中样式生效)

2 回复

你的意思是真机上生效?开发者工具不生效是吗?

我的程序中也遇到 media query 判断iPhone X,也遇到和你一样的问题。

最后同时加上了两段代码:

/* follow heigh=812px only work for real phone: iPhone X */
[@media](/user/media) screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
  .tag_max_width {
    white-space: nowrap !important;
    max-width: 220px;
  }
}
 
/* follow heigh=724px only work for weixin iPhone X emulator */
[@media](/user/media) screen and (device-width: 375px) and (device-height: 724px) and (-webkit-device-pixel-ratio: 3) {
  .tag_max_width {
    white-space: nowrap !important;
    max-width: 220px;
  }
}

使得同时让 模拟器(微信开发者工具)和 真机 都生效。

回到顶部