rem頁面布局原理詳細解說


何為rem?

相對於根元素(即html元素)font-size計算值的倍數。

通俗的說,1rem = html的font-size值

例如,下這段代碼。a標簽的font-size值為0.5rem,實際就是100px*0.5=50px。

html{
    font-size:100px;
}
a{
    font-size:.5rem;
}

如何使用rem進行布局?

  1. 標簽的rem單位的值怎么計算

通過使用  rem  +   js  改變html標簽的font-size(整體縮放)實現兼容性更高的頁面

下面來舉個例子,

當我們拿到的設計圖是750px的時候,窗口寬度750px,html的font-size的大小為100px;

也就是說1rem = 100px;所以標題的font-size的大小為26/100=.26rem;

 

 

 

h3{
    font-size:.26rem;
}

  2. 如何實現兼容各種屏幕大小的設備

使用到javascript來動態改變html標簽font-size的大小,其他的rem單位的數值就會被瀏覽動態計算轉為px單位,從而達到和設計圖高度的相似。

當屏幕750px的時候,html的font-size值是100px;窗口大小變化的時候,可以通過js獲取到窗口大小。

這時候獲取到一個比例

          750:100=獲取到的屏幕大小:html標簽的px單位的值

以下js代碼,用於實現根據獲取到的屏幕大小,動態修改html標簽的px單位的值

;(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 = 640;
        };
        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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM