CSS - 了解一下 REM

前言

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

这篇文章主要介绍了:html

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

Rem-Based Layout

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

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 的区别

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

rem 就是能够随时拿来用的一个固定参考值sass

怎么去计算 rem

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

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。iphone

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

  • 使用JS来获取屏幕宽度的好处在于能够100%适配全部的机型宽度,由于其元素的基准尺寸是直接算出来的。字体

媒体查询

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

@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单位。

参考

相关文章
相关标签/搜索