CSS: 了解一下 REM

2,554 阅读3分钟

前言

为了了解移动端的布局兼容,特地来看看 REM.

这篇文章主要介绍了:

- rem 的基础,
- 和 em 的对比
- js的解决方案 - flexable.js 
- scss 和 less 的兼容办法

Rem-Based Layout

先看看 rem 兼容性(基本上所有主流的浏览器都支持)-caniuse.com/#feat=rem

font size of the root element

  • 上面的这句话意思就是我们在指定一个 html 根元素的 font-size 的时候,我们指定一个其他的页面元素为 2rem 的时候就是字体元素的 2 倍大小
  • 看下面的例子

/*
* 基本元素: 12px
*/
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*/


/*
* 基本元素: 16px
*/
html {font-size: 16px;}
h1 { font-size: 2rem; } /* 2 × 16px = 32px */
p { font-size: 1.5rem;} /* 1.5 × 16px = 24px */
div {width: 20rem;} /* 20 * 16px = 320px*/

来看看 rem 和 em 的区别

单位定义特点
remfont size of the root element以根元素字体大小为基准
emfont size of the element以自身元素字体大小为基准

rem 就是可以随时拿来用的一个固定参考值

怎么去计算 rem

通过 JavaScript 读取屏幕宽度,然后根据宽度计算出对应的尺寸并设置根元素的 font-size

const oHtml = document.getElementByTagName('html')[0];

const width = oHtml.clientWidth;

// 320px 的屏幕基准像素为 12px
oHtml.style.fontSize = 12 * (width / 320) + "px";
  • 这样iphone8(375px)下html的font-size 就是14.0625px,iphone8p下font-size就是15.525px。

  • 如果在iphone8(375px)下设置元素font-size为 1.7066rem, 效果跟设置其font-size为 24px 是一样的(24 / 14.0625 = 1.7066)。

  • 使用JS来获取屏幕宽度的好处在于可以100%适配所有的机型宽度,因为其元素的基准尺寸是直接算出来的。

媒体查询

既然是根据屏幕的宽度来设置元素的大小,大部分同学应该想到的是 css3 的媒体查询来解决这个问题,其实这种方法也是我们最常用的解决方案之一。

@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;
}

用 SASS 和 LESS 方法去更好的时候用 REM

  • 我们先设置一个 font-size 的方法
// css 
html {
  font-size: 62.5%; /* 基础的 font-size: 10px */
}

// less
.font-size(@sizeValue) {
  @remValue: @sizeValue;
  @pxValue: (@sizeValue * 10);
  font-size: ~"@{pxValue}px"; 
  font-size: ~"@{remValue}rem";
}

// sass
@mixin font-size($sizeValue: 1.6) {
  font-size: ($sizeValue * 10) + px;
  font-size: $sizeValue + rem;
}
  • 具体的用法
// less
p {
  .font-size(13);
}

// sass
p {
  @include font-size(13);
}

rem 自适应 js

应用

  • 需要兼容大部分移动端,文字和图片较多的应用,比如淘宝,小说网之类的应用可以使用这种方法

我们平时使用rem还有遇到的一大问题就是我们习惯使用px来定义样式,而px到rem是需要计算转化过程的,刚接触rem的时候你可能需要px先定义好页面布局,然后一个一个计算并替换rem单位。

参考