前一段時間羣裏有人問我rem相關的問題,一直想整理一下,但是都忘記了.今天終於抽出時間來整理一下相關知識點!
說到rem就要談到移動端佈局,如今不少人在移動端佈局上面仍是用px,咱們先來談談px;px:像素(Pixel),相對單位長度,px相對於屏幕分辨率而言的.
咱們爲何使用rem,rem的誕生也是webapp的推進,rem完美解決了webapp的屏幕適應問題,你們都知道移動端設備屏幕大小各異,像素也是各個不一樣的,那麼webapp使用px就至關雞肋,由於你們都知道px是像素,由屏幕的分辨率決定,用px在很大程度上影響webapp的美觀.
下面介紹如何使用rem,首先咱們得設置rem的初始值,而後咱們每一個尺寸按照這個初始值進行換算得出rem值進行佈局.
1.媒體查詢html
html { font-size : 20px; } @media only screen and (min-width: 401px){ html { font-size: 25px !important; } } @media only screen and (min-width: 428px){ html { font-size: 26.75px !important; } } @media only screen and (min-width: 481px){ html { font-size: 30px !important; } } @media only screen and (min-width: 569px){ html { font-size: 35px !important; } } @media only screen and (min-width: 641px){ html { font-size: 40px !important; } }
2.自動設置html的font-sizeweb
(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);
3.designWidth:設計稿的實際寬度值,須要根據實際設置,maxWidth:製做稿的最大寬度值,須要根據實際設置瀏覽器
(function(designWidth, maxWidth) { var doc = document, win = window, docEl = doc.documentElement, remStyle = document.createElement("style"), tid; function refreshRem() { var width = docEl.getBoundingClientRect().width; maxWidth = maxWidth || 540; width>maxWidth && (width=maxWidth); var rem = width * 100 / designWidth; remStyle.innerHTML = 'html{font-size:' + rem + 'px;}'; } if (docEl.firstElementChild) { docEl.firstElementChild.appendChild(remStyle); } else { var wrap = doc.createElement("div"); wrap.appendChild(remStyle); doc.write(wrap.innerHTML); wrap = null; } //要等 wiewport 設置好後才能執行 refreshRem,否則 refreshRem 會執行2次; 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);