em:相对于父元素的字体大小
rem:相对于根节点元素来计算的。
js动态适配
<div id="demo"></div>
*{
margin:0;
padding:0
}
#demo{
width:3.45rem;
height:1.5rem;
margin: 0.15rem auto 0;
background-color:green;
}
//封装函数
function adapter(){
const dpWidth = document.documentElement.clientWidth
//第一种写法
const rootFrontSize = (dpWidth * 100)/ 375 //375:设计稿的宽度
//第二种写法 const rootFrontSize = dpWidth /10
document.documentElement.style.fontSize = rootFrontSize
}
//调用
adapter()
//实时适配
window.onresize=()=>{
adapter()
}
第二种写法配合less版本
less:
@fontsize:375/10rem
*{
margin:0;
padding:0
}
#demo{
width:375/@fontSize;
height:150/@fontSize;
margin: 15/@fontSize auto 0;
background-color:green;
}
//可编译成:
*{
margin:0;
padding:0
}
#demo{
width:9.2rem;
height:4rem;
margin: 0.4rem auto 0;
background-color:green;
}