前言
为了了解移动端的布局兼容,特地来看看 REM.
这篇文章主要介绍了:
- rem 的基础,
- 和 em 的对比
- js的解决方案 - flexable.js
- scss 和 less 的兼容办法
先看看 rem 兼容性(基本上所有主流的浏览器都支持)-https://caniuse.com/#feat=rem
font size of the root element
/*
* 基本元素: 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 | font size of the root element | 以根元素字体大小为基准 |
em | font size of the element | 以自身元素字体大小为基准 |
rem 就是可以随时拿来用的一个固定参考值
通过 JavaScript 读取屏幕宽度,然后根据宽度计算出对应的尺寸并设置根元素的 font-size
const oHtml = document.getElementByTagName('html')[0];
const width = oHtml.clientWidth;
// 320px 的屏幕基准像素为 12px
oHtml.style.fontSize = 12 * (width / 320) + "px";
既然是根据屏幕的宽度来设置元素的大小,大部分同学应该想到的是 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;
}
// 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还有遇到的一大问题就是我们习惯使用px来定义样式,而px到rem是需要计算转化过程的,刚接触rem的时候你可能需要px先定义好页面布局,然后一个一个计算并替换rem单位。