移动端通过 rem适配多种机型

1rem 默认 = 16px,因为 浏览器默认的字体是 16px
字体大小跟着 html根元素变化
动态修改 html的font-size来修改 rem
image.png
image.png

rem的基准值

  • rem数值计算
  • rem与 scss的结合

rem的基准值,就是 html的 font-size,默认是 16px

rem与scss的结合

px2rem

  1. @function px2rem($px) {
  2. $rem: 37.5px;
  3. @return ($px / $rem) + rem;
  4. }
  5. .main {
  6. width: px2rem(100px);
  7. height: px2rem(100px);
  8. }

动态修改font-size

js动态修改 font-size

  1. // 获取视口宽度
  2. const clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
  3. const html = document.querySelector('html');
  4. html.style.fontSize = `${clientWidth/10}px`;
  1. document.addEventListener('DOMContentLoaded', () => {
  2. // 获取视口宽度
  3. const clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
  4. const html = document.querySelector('html');
  5. const fontSize = (clientWidth/10) > 50 ? 50px (clientWidth/10);
  6. html.style.fontSize = `${fontSize}px`;
  7. });
  8. window.addEventListener('resize', () => {
  9. });

mediaQuery

css的优先级,和顺序有关,顺序在后面的,权重要高
mediaQuery的缺点:

  • 手机碎片化严重,要写很多的 mediaQuery ```css @media screen and (max-width: 768px) { html {
    1. font-size: 20px;
    } }

// 指定宽高 @media screen and (max-width: 320px) and (min-height: 578px) { html { font-size: 16px; } } ```