动态rem适配屏幕

605 阅读1分钟

一、rem与px的换算关系

rem和px都是css单位。px是固定单位,rem是相对单位。对于需要适配屏幕等比缩放的元素可以选用rem作为单位,对于不需要等比缩放的元素依旧使用px作为单位。
1rem等于html根元素设定的font-size的px值
如果css里面没有设定html的font-size,则默认浏览器以1rem=16px来换算。

二、如何适配屏幕

算法:

image.png Wp是页面有效宽度,Hp是页面有效高度;页面左右居中,上下居中,四周留空白即可。 在head里面用js设置1rem = Wp /100

用rem:

image.png

代码:

<head>
  <script>
    //获取屏幕的宽高
    const clientWidth = document.documentElement.clientWidth
    const clientHeight = document.documentElement.clientHeight
    //根据公式计算
    window.pageWidth = clientWidth / clientHeight > 16 / 9 ? clientHeight * (16 / 9) : clientWidth
    const pageHeight = pageWidth / (16/9)
    //设置1个rem是宽度的1%,插入到页面中
    const string = `<style>
        html{
          font-size:${pageWidth / 100}px
        }
      </style>`
      document.write(string)
  </script>
</head>

<body>
<div id="root"></div>
<script>
  root.style.height = pageHeight + 'px'
  root.style.marginTop = (clientHeight - pageHeight) / 2 + 'px'
</script>
</body>