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即为1rem16px即为0.16rem等等。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注