REM这个单位,会根据html的font-size大小进行转换。
html{font-size:100px;}
p{padding-top:.5rem;}
转换后p的padding-top就是50px了。只要我们进行适当的计算,当前屏幕的宽度,html的font-size是多少px就OK了。
计算rem基准的js
//定义basesize来实现rem
(function(doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
var clientWidth = docEl.clientWidth,
remBaseize = 40 * (clientWidth / 750),
remBaseize = remBaseize > 60 ? 60 : remBaseize;
if (!clientWidth) return;
docEl.style.fontSize = remBaseize + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
sass自定义计算rem
@function rem($px) {
$remSize :$px/40;
@return #{$remSize}rem;
}
.main-page {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
height: rem(500);
background-color: yellow;
.test {
width: rem(150);
height: rem(120);
background-color: blue;
}
}