首先要知道:rem 和 em 是相对单位;
我们通过代码来看 rem 和 em的使用和区别:
em:相对于父级
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>this is a test file</title>
<style type="text/css">
html,body{font-size:16px;}
</style>
</head>
<body>
<p>test 16px</p>
<div style="font-size:2em;">test
<p style="font-size:2em;">test</p>
</div>
</body>
</html>
显示效果:
我们可以看到,首先我们重置浏览器的默认显示字体大小为16px( 即便默认显示大小也是16px );
body中的第一个段落标签的字体大小也就是16px;
div的字体大小设为 2em ,也就是说div的字体大小是其父级的2倍,父级body是16px,那么div
的字体大小就是16*2=32px ;
div中的段落p 的字体大小设为2em,也就是说段落p 的字体大小是其父级的2倍,那么也就是div
字体大小的2倍,是32*2=64px ;
所以说em是相对于其父级的大小单位;
rem是相对于根的大小单位
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>this is a test file</title>
<style type="text/css">
html{font-size:16px;}
</style>
</head>
<body>
<p>test 16px</p>
<div style="font-size:2rem;">test
<p style="font-size:2rem;">test</p>
</div>
</body>
</html>
显示效果:
我们来看首先我们设置html{font-size:16px;} 这个就是根了,rem就是相对于这个大小的,
body中第一个段落p的字体大小为16px;
body中div的字体大小我们设置为2rem,那么就是根的2倍,即 16px * 2=32px;
body中div中的段落p的字体大小我们设置为2rem,那么就是根的2倍,即16px *2=32px;
总结:em是相对于父级元素的单位
rem是相对于根元素的单位