rem之移动端布局
rem
在MDN上解释为
rem values are relative to the root html element, not the parent element.
它是基于根元素(html
)的字体大小来计算,在默认情况下,html
的字体大小为16px
,所以如果我想设置一个元素大小为14px
,进行一个简单的计算14/16=0.875
,即设置0.875rem
。根据这个特性,可以通过如下方式计算,来使用不同设计稿的大小进行布局。
(function (window) {
var designWidth = 750, //
maxWidth = 750,
document = window.document,
width = document.body.clientWidth || document.documentElement.clientWidth,
htmlEl = document.getElementsByTagName('html')[0],
ev = 'orientationchange' in window ? 'orientationchange' : 'resize',
changeView = function () {
var w = width || 320;
if (w > maxWidth) w = maxWidth;
htmlEl.style.fontSize = w * 100 / designWidth + 'px';
};
if (document.addEventListener) {
window.addEventListener(ev, changeView, false);
document.addEventListener('DOMContentLoaded', changeView, false);
} else if (document.attachEvent) {
window.attachEvent(ev, changeView);
document.attachEvent('onDOMContentLoaded', changeView)
} else {
window['on' + ev] = changeView;
document['onDOMContentLoaded'] = changeView;
}
}(window));
通过设置设计稿宽度designWidth
和页面最大缩放大小maxWidth
的值,即可针对任意大小的设计稿来进行页面布局,使用rem
基本上可以保证不同的尺寸表现方式一致。
为了方便计算,通常将根元素的字体大小设置为100px
,即
:root {
font-size: 625%;
}
这样,设计稿上的100px
即为1rem
,16px
即为0.16rem
等等。
如果您觉得本文对您有用,欢迎捐赠或留言~
- 本博客所有文章除特别声明外,均可转载和分享,转载请注明出处!
- 本文地址:https://www.leevii.com/?p=1063