整理笔记7: CSS移动端响应式布局

168 阅读1分钟

CSS移动端响应式布局

我是knockkey, 这是我坚持更新博客第2天. 这篇博客介绍实现响应式的基本点

1. rem是什么?

  • px: 绝对长度单位, 最常用
  • em: 相对长度单位, 相对于父元素, 不常用
  • rem: 相对长度单位, 相对于根元素, 常用于响应式布局

2. 响应式布局常见方案

媒体查询 media-query (根据不同的屏幕宽度设置根元素 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>
    @media only screen and (max-width:374px) {
      /* iphone5 或者更小的尺寸, 以 ipone5 的宽度(320px) 比例设置 font-size */
      html {
        font-size: 86px;
      }
    }

    @media only screen and (min-width:375px) and (max-width:413px) {
      /* iphone6/7/8 和 iphoneX */
      html {
        /* 以iphone6为标准, 374/375 = 86/100 比例计算出来的 */
        font-size: 100px;
      }
    }

    @media only screen and (min-width:414px) {
      /* iphone6p 或者更大的尺寸, 以iphone6p的宽度(414px) 比例设置 font-size */
      html {
        /* 375/414 = 100/110 */
        font-size: 110px;
      }
    }

    body{
      /* 在iphone6上就是0.16*100 在iPhone5上就是0.16*86 */
      font-size: 0.16rem;
    }
    #div1{
      /* 同理 在iPhone6上就是100px */
      width: 1rem;
      background-color: pink;
    }
  </style>
</head>

<body>
  <div id="div1">
    this is div
  </div>
</body>

</html>

3. rem的弊端

  • 具有阶梯性的 不同的屏幕不同大小

4.vm vh vmax vmin(无阶梯性)

  • 屏幕高度: window.screen.heigth
  • 网页视口高度 可以显示内容的高度: window.innerHeight === 100vh
  • body高度: document.body.clientHeight
  • vh网页视口高度的1/100
  • vw网页视口宽度的1/100
  • vmax 取两者的最大值 vmin取两者的最小值 应用于把手机横过来