rem方案实现页面宽高自适应

rem方案实现页面宽高自适应

问题引入及解决

最近做大屏项目,有一个现实问题:不同屏幕如何保证页面按 16:9 显示。

由于不同设备屏幕尺寸分辨率不同,或者需要考虑横竖屏问题,为了使得web页面在不同移动设备上具有相适应的展示效果,需要在开发过程中使用合理的适配方案来解决这个问题。

rem方案提供了较好的解决办法:

根据页面宽高比16:9,

  1. 当设备较宽时,w设备/h设备 > 16/9,此时页面高度即为设备高度
  2. 当设备较高时,w设备/h设备 <= 16/9,此时页面宽度就是设备宽度

因此,有如下计算方法:

页面宽高计算方法

其中,Wp 为页面有效宽度,Hp 为页面有效高度

页面左右居中,上下居中,四周留白即可

然后,在 中设置字体按比例缩放 1rem = W / 100 ,即可达到效果。

代码实现

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<head>
<script>
// 采用动态rem方案响应页面布局
const clientWidth = document.documentElement.clientWidth;
const clientHeight = document.documentElement.clientHeight;
const pageWidth = clientWidth / clientHeight > 16 / 9 ? clientHeight * 16 / 9 : clientWidth;
const pageHeight = pageWidth * 9 / 16;
// 设置 1rem = pageWidth/100
const string = `
<style>
html{
font-size: ${pageWidth / 100}px;
}
</style>
`;
// 将style标签写入页面
document.write(string);
</script>
</head>
<body>
<div id="root"></div>
<script>
// 设置root宽高
root.style.width = pageWidth + "px";
root.style.height = pageHeight + "px";
root.style.background = "pink";
// 设置root上下居中
root.style.marginTop = (clientHeight - pageHeight) / 2 + "px";
// 设置root左右居中(可以直接写在css中)
root.style.marginLeft = "auto";
root.style.marginRight = "auto";
</script>
</body>

使用 rem 代替 px

当使用宽高自适应响应式布局之后,就不能使用 px 单位将每个元素尺寸写死了,此时就需要用 rem 来计算元素的尺寸。

根据页面与设计稿的尺寸与宽度之比相等,可知:

使用rem代替px

因此,页面尺寸只需通过如下px函数就能计算得到:

1
2
3
@function px($n) {
@return $n / widthDesign * 100rem;
}

其中,$n 为设计稿实际尺寸;

​ 常量 widthDesign 为设计稿实际宽度,由实际测量得到。


版权声明:本文作者为「Andy8421」.本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!