em是相对单位,它的值是相对于元素的字体大小。如果元素没有设置字体大小,则继承父元素的字体大小
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.parent {
font-size: 16px;
}
.child {
font-size: 1.5em;
width: 2em;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Hello, World!</div>
</div>
</body>
</html>
.child 元素的字体大小设置为 1.5em,由于其父元素 .parent 的字体大小是 16px,所以 .child 元素的字体大小实际为 16px * 1.5 = 24px。
.child 元素的宽度设置为 2em,此时的 em 基于 .child 自身的字体大小 24px,所以 .child 元素的宽度实际为 24px * 2 = 48px。
HTML中,rem是相对于根元素的字体大小
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
html {
font-size: 20px;
}
.box {
width: 3rem;
}
</style>
</head>
<body>
<div class="box">This is a box.</div>
</body>
</html>
.box 元素的宽度设置为 3rem,因为根元素 的字体大小是 20px,所以 .box 元素的宽度实际为 20px * 3 = 60px。
浙公网安备 33010602011771号