字体单位:值根据html根元素大小而定,同样可以作为宽度、高度等单位
适配原理:将px替换成rem,动态修改html的font-size适配
兼容性:ios6以上和android2.1以上,基本覆盖所有流行的手机系统
浏览器的默认字体是16px,也就是说1rem=16px
通过媒体查询设置html的font-size有缺点,页面的变化是根据媒体查询走的,没有js动态设置的更加细致
通过js动态设置html的font-size
let htmlWidth=document.documentElement.clientWidth || document.body.clientWidth;//获取视窗宽度
let htmlDom=document.getElementsByTagName('html')[0];
htmlDom.style.fontSize=htmlWidth/10+'px';//iphone6的宽度375除以10是37.5,与scss中function里面的$rem基准值一致
window.addEventListener('resize',(e)=>{
let htmlWidth=document.documentElement.clientWidth || document.body.clientWidth;
htmlDom.style.fontSize=htmlWidth/10+'px';
})
全局安装node-sass:npm install node-sass -g
a.scss转化成b.css:node-sass a.scss b.css
a.scss里面通过function自动把px计算成rem值
@function px2rem($px){
$rem:37.5px;/*以iphone6的375为基准*/
@return ($px/$rem)+rem;
}
.hello{
width:px2rem(100px);height:px2rem(100px);font-size:px2rem(18px);
}
字号,宽高,margin,padding等,只要是用到px的地方,都可以写成rem
我完整的实现了一遍,如需要源码,可以下载 https://github.com/jiechud/notes/tree/master/html/Demo/rem 如果帮助,欢迎 star