rem是相对于根元素html发生变化的,比如
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
html{
font-size: 10px;
}
div{
font-size:1.5rem;/*1.5 * 10 = 15px*/
width: 15rem;/*15 * 10 = 150px*/
height: 15rem;/*15 * 10 = 150px*/
background: #ADD8E6;
}
p{
font-size: 1.2rem;/*1.2 * 10 = 12px*/
}
</style>
</head>
<body>
<div>
我是div的内容
<p>
我是p标签里面的内容
</p>
</div>
<script>
(
function(){
var timeoutId;
function setRem(){
var clientWidth = document.documentElement.clientWidth;//设备宽度
var nowPX = clientWidth / 320 * 10;//这里以320px宽度为标准开发,320px宽度为10px 其它宽度则根据比例计算
document.documentElement.style.fontSize = nowPX + "px";//设置根元素html字体大小
}
setRem();
//窗体大小改变监听事件
window.addEventListener("resize",function(){
clearTimeout(timeoutId);
timeoutId = setTimeout(function(){
setRem();
},300)
},false)
}
)();
</script>
</body>
</html>
这样,单位就能够根据设备大小相应变化。