1、em
html:
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
css:
<style>
.div1 {
background-color: lightblue;
width: 10em;
height: 10em;
/*10em=160px
1em=16px */
}
.div2 {
background-color: lightpink;
height: 160px;
width: 160px;
}
</style>
效果如下:
由以上结果可知,在沒有設置任何字体大小的时候,1em直接继承浏览器的字体大小16px.
html:
<div class="div1">
<div class="div2"></div>
<div class="div3"></div>
</div>
css:
<style>
.div1 {
background-color: lightblue;
width: 10em;
height: 10em;
font-size: 20px;
}
.div2 {
background-color: lightpink;
height: 5em;
width: 5em;
/* 5em=100px;
1em=20px; */
/* height: 10em;
width: 10em;
font-size: 10px; 效果一样 */
}
.div3 {
background-color: lightgreen;
height: 100px;
width: 100px;
}
</style>
如果元素本身设置了字体大小,会先找元素本身的大小,如果没有则继承父元素的字体大小,如果父元素也没有则找根元素。
2、rem
html:
<div class="div1">恭喜发财</div>
<div class="div2">恭喜发财</div>
<div class="div3">恭喜发财</div>
<div class="div4">恭喜发财</div>
<style>
html{
color: red;
font-size: 1rem;
/* 1rem=16px */
}
.div1{
font-size: 2rem;
}
.div2{
font-size: 32px;/* 2rem=32px */
}
.div3{
font-size: 3rem;
}
.div4{
font-size: 48px;/* 3rem=48px */
}
</style>
由效果可知,div1和div2字體大小是相等的,div3和div4字體大小是相等的,
<style>
html{
color: red;
font-size: 2rem;
/* 2*16=32px */
}
.div1{
font-size: 2rem;
}
.div2{
font-size: 64px;
/* 2*32=64px */
}
.div3{
font-size: 3rem;
}
.div4{
font-size: 96px;
/* 3*32=96px */
}
</style>
当根元素设置为2rem时,相当于以32px为标准,设置字体大小倍数。
3、总结
em:
相对单位,参考量是从自己开始向父级寻找设置的字体大小,父级没有则找根元素。
rem:
rem是指相对于根元素的字体大小的单位。在根元素中使用是设置参考量,其他子元素使用时是相对于根目录设置字体大小的倍数。
作用:利用rem可以实现简单的响应式布局,可以利用html元素中字体的大小与屏幕间的比值设置font-size的值实现当屏幕分辨率变化时让元素也变化,以前的天猫就使用这种办法。
em与rem的重要区别: 它们计算的规则一个是依赖父元素另一个是依赖根元素计算。