理解 rem 方案原理

理解 rem 方案原理,第1张

设计师交付给html" class="superseo">前端开发一张宽度为750px的视觉稿,设计稿上元素的尺寸、颜色、位置等已做过标注,要求工程师工在适配不同屏幕尺寸的设备时采用等比缩放的方案。

首先设计稿是基于 iPhone6 设计的也就是宽度 750px。(先不考虑dpr的问题下面会说)然后设置 1rem 等于 100px( HTML font-size 为 100px),相当于 7.5rem = 100%宽度 = 设备的宽度。

750 / 7.5 = 100

由于是基于 7.5rem 开发。iPhone6 的物理像素是 375px(dpr是2.0),如果此时还想让 7.5rem 等于设备宽度只能调整 1rem 对应 font-size 的比例, 375 / 7.5 = 50 让 1rem=50px 就可以实现。

如果想让 iPhone5 适配只需要 1rem = (320 / 7.5) = 42.66px 就可以实现 iPhone5 的适配,这个方法可以适配市面上绝大多数的移动端设备。

只需要加下面这句话可以实现我上述效果。

document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px';

动态计算并设置不同尺寸 html 的 font-size 属性(大白话:动态计算出来不同手机页面的 html 的font-size)。动态 rem 方案既能实现页面级整体缩放,又能个性化控制某些元素不缩放。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html {
      font-size: 100px;
    }

    body {
      font-size: 16px;
    }

    .root {
      max-width: 750px;
      margin: 0 auto;
    }

    .box {
      width: 7.02rem;
      height: 2.06rem;
      border-radius: 0.24rem;
      background: red;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <div class="root">
    <div class="title">hello</div>
    <div class="box"></div>
  </div>
  <script>
    window.addEventListener('resize', () => {
      calculate()
    })
    function calculate(isFirst) {
      const width = document.documentElement.clientWidth
      const value = width > 750 ? 750 : width
      document.documentElement.style.fontSize = value / 7.5 + 'px'
    }
    calculate()
  </script>
</body>

</html>

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/2990022.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存