行動版網頁要讓同一套設計稿在不同尺寸的手機上都呈現一致比例,核心思路是讓根元素的 font-size 隨視窗寬度縮放,再用 rem 作為所有尺寸的單位。以下整理三種常見做法。
(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 = 100 * (clientWidth / 750) + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
這段程式以 750 為設計稿基準寬度,換算後 1rem 在 375px 的裝置上剛好等於 50px。對照關係是:100px = 1rem、10px = 0.1rem、1px = 0.01rem。
綁定 orientationchange 是為了應付螢幕旋轉;同時監聽 DOMContentLoaded 則是確保首次渲染時字級已就位。
(function (win) {
function setUnitA() {
document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + "px";
}
var h = null;
window.addEventListener("resize", function () {
clearTimeout(h);
h = setTimeout(setUnitA, 300);
}, false);
setUnitA();
})(window);
這裡把根字級設為視窗寬度的十分之一,寫死的 px 則交給 Less 換算。在 Less 檔案頂部定義:
@unit: 750/10rem;
之後樣式中直接寫 width: 100px/@unit 即可,編譯後自動變成 rem。相應的換算為:100px = 100/@unit、10px = 10/@unit、1px = 1/@unit。
這裡的 clearTimeout + 300ms 是簡易的 debounce,避免 resize 高頻觸發時反覆重排。
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; } }
@unit: 40rem;
不用一行 JavaScript,靠斷點硬切。優點是簡單可靠、沒有效能負擔;缺點是斷點之間仍是跳階而非平滑縮放,且斷點需要人工維護。
vw 單位,一行 html { font-size: calc(100vw / 7.5); } 就能取代方案一;若搭配 postcss-pxtorem 這類自動轉換工具,連 Less 變數都能省下。另外別忘了加上 min-width 限制,避免在平板或桌機上字級被放大到失控。無論採用哪一種,都要注意:字級縮放的同時,可點擊區域不宜小於 44px、正文行高與字級需同步調整,這才是真正可用的適配。