移动端适配之REM



  • 先看看为什么移动端要做适配,以及什么是适配?
    下面看看一段CSS在不同移动设备上的表现:

    .title {
      font-size: 28px;
      font-weight: 500;
      color: black;
    }
    p {
      font-size: 16.8px;
      color: gray;
    }
    

    (1)iphone6/7/8
    替代文字

    (2)ipad
    替代文字
    比较起来,在ipad上的显示好像不那么如人意。

    所以,简单的说,移动端适配就是为了让同一个网页能在不同的机型,不同宽高比的设备上都能较好的显示。

    接下来我们就来看看一个移动端适配常用的方法——rem。

    什么是rem?

    font size of the root element

    rem就是一个类似px的像素单位,只不过它是相对于根元素的font-size进行定义的。

    rem常常和em做对比:

    单位 定义 特点
    rem font size of the root element 以根元素字体大小为基准
    em font size of the element 以父元素字体大小为基准

    虽然em带来了模块化的好处,但是由于 em 是相对于父元素的倍数,所以你可能在许多层嵌套的 em 中找不到一个固定值rem 就是可以随时拿来用的一个固定参考值。

    html {font-size: 12px;}
    h1 { font-size: 2rem; } /* 2 × 12px = 24px */
    p { font-size: 1.5rem;} /* 1.5 × 12px = 18px */
    div {width: 20rem;} /* 20 * 12px = 240px*/
    

    rem计算

    我们发现,使用rem单位事先需要做的一件事情就是设置根元素<html>的font-size,通常有两种做法:

    1. JS计算

    const oHtml = document.getElementsByTagName('html')[0]
    const width = oHtml.clientWidth;
    // 320px的屏幕基准像素为12px
    oHtml.style.fontSize = 12 * (width / 320) + "px";
    

    2. 媒体查询

    通过css3媒体查询,根据屏幕宽度来设置<html>元素的字体大小

    @media screen and (min-width: 375px){
        html {
            font-size: 14.0625px;   
        }
    }
    @media screen and (min-width: 360px){
        html {
            font-size: 13.5px;
        }
    }
    @media screen and (min-width: 320px){
        html {
            font-size: 12px;
        }
    }
    html {
        font-size: 16px;
    }
    

    下面看看使用rem的效果:
    (前提:已动态设置了html根元素的font-size大小)

    .title {
      font-size: 2rem;
      font-weight: 500;
      color: black;
    }
    p {
      font-size: 1.2rem;
      color: gray;
    }
    

    iphone6/7/8
    替代文字
    ipad
    替代文字
    相比写固定的px,使用相对单位rem的效果确实要好一些~


 

Copyright © 2018 bbs.dian.org.cn All rights reserved.

与 Dian 的连接断开,我们正在尝试重连,请耐心等待