em 是一个相对的距离单位
参考父级的font-size
1em == 父级的 1 * font-size
备注:em 通过自身父级的字体大小, 会转换为px
公式: 实际px == 1em * 父级的字体大小
优点: 方便我们设置段落间隙
缺点: 当嵌套多层的时候,需要自己去计算
rem: 和em基本类似,区别点在于: em相对自身父级的字体, rem只相对html的字体大小
rem: root-em 根元素的em值, html的字体大小
<meta name="viewport" content="width=device-width,initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">
<style>
html{
font-size: 20px;
}
.main{
width: 2rem;
height: 2rem;
background: gold;
}
.box{
width: 200px;
height: 200px;
border: 1px solid;
font-size: 20px;
}
.min_box{
width: 6em;
height: 5em;
background: red;
}
</style>
<body>
<div class="box">
<!--rem-->
<div class="main"></div>
<!--em-->
<div class="min_box"></div>
</div>
<body>
rem 计算公式:
1) 屏幕的宽度(设计稿 通常是750) / 份数(20) = html的字体大小(1rem的大小)
2)元素的尺寸 / 1rem的值 = 实际的rem值(要写在元素样式上的值)
<script>
var htmlWidth = window.screen.width;
window.onresize = function (ev) {
//一些浏览器中,无法获取到documentElement, 所以去获取body
var htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
// 获取html 便于下面设置html的字体大小
var html = document.querySelector("html");
//设置根元素的字体大小
html.style.fontSize = htmlWidth / 20 +'px';
}
</script>