现在使用PX都不怎么适应手机端,自从有了rem之后,彻底告别px,rem的大小是随着HTML的font-size打大小来决定的,所以,在不同宽度的设备,用JS改变html的font-size就可以完美的使用rem了。
可以直接复制我下面那段html来预览demo。
1rem = html的font-size的大小
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
//设置HTML的font-zise
(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);
//end
</script>
</head>
<body>
<p style="font-size:0.5rem">html的font-size会随着窗口大小变化而改变, JS就上面那一段而已。</p>
<p style="font-size:0.5rem">1rem = html的font-size</p>
<button style=" padding:0.2rem 0.5rem; background:#eee; font-size:0.6rem">我是按钮</button>
</body>
</html>