关于rem布局摘录

前言:

一般情况下使用em或者rem的时候,会写个样式:html,body{font-size:62.5%} / html{font-size:62.5%},这样设置方便了em、rem与px相互转换,因为浏览器默认字体大小16px,所以em的初始值为1em=16px。当设置了body{font-size: 62.5%;}时,1em则=16px*62.5%=10px。但是由于谷歌不兼容,所以我个人习惯使用 html{font-size:100px}。

目前有两种适配方式:

  1. 根据js来调整html的字体大小;
  2. 另一种则是通过媒体查询来调整。

使用js:

1、推荐使用,兼容性好

(function(designWidth, maxWidth) {
    var doc = document,
        win = window;
    var docEl = doc.documentElement;
    var tid;
    var rootItem,rootStyle;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
        if (!maxWidth) {
            maxWidth = 540;
        };
        if (width > maxWidth) {
            width = maxWidth;
        }
        var rem = width * 100 / designWidth;
        //兼容UC开始
        rootStyle="html{font-size:"+rem+'px !important}';
        rootItem = document.getElementById('rootsize') || document.createElement("style");
        if(!document.getElementById('rootsize')){
        document.getElementsByTagName("head")[0].appendChild(rootItem);
        rootItem.id='rootsize';
        }
        if(rootItem.styleSheet){
        rootItem.styleSheet.disabled||(rootItem.styleSheet.cssText=rootStyle)
        }else{
        try{rootItem.innerHTML=rootStyle}catch(f){rootItem.innerText=rootStyle}
        }
        //兼容UC结束
        docEl.style.fontSize = rem + "px";
    };
    refreshRem();

    win.addEventListener("resize", function() {
        clearTimeout(tid); //防止执行两次
        tid = setTimeout(refreshRem, 300);
    }, false);

    win.addEventListener("pageshow", function(e) {
        if (e.persisted) { // 浏览器后退的时候重新计算
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);

    if (doc.readyState === "complete") {
        doc.body.style.fontSize = "16px";
    } else {
        doc.addEventListener("DOMContentLoaded", function(e) {
            doc.body.style.fontSize = "16px";
        }, false);
    }
})(750, 750);

要点:

  • rem的值等于:(设备的宽度) x (字体大小) / (设计稿宽度)

2、相对简便

(function (doc, win) {
  var docEl = doc.documentElement,
  resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
  recalc = function () {
  var clientWidth = docEl.clientWidth;
  if (!clientWidth) return;
    docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
  };

  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false);
  doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

使用media:

html {font-size: 62.5%}

@media only screen and (min- 481px) {
html {font-size:40%!important}
}

@media only screen and (min- 561px) {
html {font-size:46.7%!important}
}

@media only screen and (min- 641px) {
html {font-size:53.3%!important}

@media only screen and (min- 751px) {
html {font-size:62.5%!important}

body {max- 750px}
}

要点:

  • 换算公式:(设备的宽度) / (设计稿宽度) x (字体大小) / (16)

参考资料:

原文地址:https://www.cnblogs.com/geewonii/p/7341722.html