移动端自适应方案—rem布局

1、什么是rem

rem(font size of the root element)是一个相对单位,它是根据根元素(html)的font-size大小来计算的,如根元素字体大小为10px,那么1rem = 10px

em(font size of the element)也是一个相对单位,它是根据父元素的字体大小来计算的。

举个例子,如果我们想让ul标签的font-size是12px,我们先把html标签font-size设置为16px,然后可以这样使用rem单位

html {
  font-size: 16px;
}

ul {
  font-size: 0.75rem;    /* 12px */
}

如果ul标签中嵌套 li 标签,li标签的font-size是6px

html {
  font-size: 16px;
}

ul {
  font-size: 0.75rem;   /* 12px */
}

li {
  font-size: 0.5em;      /* 6px */
}
2、rem在响应式布局当中的使用
a)第一种改变html根元素font-size方法使用媒体查询
html {
  font-size: 62.5%;
  font-family: Arial, sans-serif;
  
  @media(min-width: 400px) {
    font-size: 100%;
  }
  @media(min- 800px) {
    font-size: 150%;
  }
}

h1 {
  margin: 0 0 2rem;
  font-size: 1.5rem;
}

p {
  margin: 0 0 1rem;
}
b)在Vue中监听设备宽度,更改根元素fontSize的大小
(function (doc, win) {
  var docEl = doc.documentElement
  var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
  var reCalc = function () {
    var clientWidth = docEl.clientWidth
    if (!clientWidth) return
    docEl.style.fontSize = 16 * (clientWidth / 320) + 'px'
  }
  if (!doc.addEventListener) return
  win.addEventListener(resizeEvt, reCalc, false)
  doc.addEventListener('DOMContentLoaded', reCalc, false)
})(document, window)

然后在main.js中引入,直接import './config/rem'导入即可,import的路径根据你的文件路径去填写。

原文地址:https://www.cnblogs.com/lcxcsy/p/13793201.html