web,h5移动端vm+rem适配

91 阅读1分钟

不用任何插件使用vm+rem实现移动端适配

适配原理

使用如下meta标签让viewport等于屏幕的大小

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

按设计图的宽度 = 设备宽度

下面一375px的设计稿为例

375px == 100vw

1px == 100vw/375 == 0.26666666vw(保留8位小数)

设置html标签的font-size为 0.26666666vw可得如下的对应关系

1rem = 0.26666666vw = 1px

我们写代码使用rem单位就对应设计稿的px单位,375rem就是屏幕的宽度

例子:

<!DOCTYPE html>
<html style="font-size: 0.26666666vw;">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>viewport+rem适配测试</title>
</head>

<body style="margin: 0;">
    <div style="background-color: red; width:100rem; height:100rem"></div>
    <div style="background-color: red; width:375rem; height:375rem;margin-top: 10rem;"></div>
</body>

</html>

微信里的效果:

20221124111058.jpg