Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Css 为什么1em不是基于定义的16px?_Css_Html - Fatal编程技术网

Css 为什么1em不是基于定义的16px?

Css 为什么1em不是基于定义的16px?,css,html,Css,Html,我在理解代码时遇到了一些严重问题: <!DOCTYPE html> <html> <head> <style> body{ font-size:16px; } p { margin: 0 0 1em 0; font-size: 2em; line-height: 1em; } </style> </head> <body> <p>Sample Text</p

我在理解代码时遇到了一些严重问题:

<!DOCTYPE html>
<html>
<head>
<style>

body{
    font-size:16px;
}
p {
    margin: 0 0 1em 0;
    font-size: 2em;
    line-height: 1em;

}
</style>
</head>
<body>

<p>Sample Text</p>


</body>
</html>

身体{
字体大小:16px;
}
p{
边际:0.01米0;
字号:2em;
线高:1米;
}
示例文本


我知道字体大小现在是32px,因为我把2em放在16的两倍,但是为什么边距底部和行距高度是32px,即使它是1em?

在您的情况下,您应该使用
rem
而不是
em

看一看

em
相对于其最近父级的字体大小,
rem
相对于根字体大小

我想把
rem
的“r”看作是“根em”。根表示
html
而不是
body
元素

console.log(“div em的填充:+window.getComputedStyle(em.padding));
log(“div rem的填充:+window.getComputedStyle(rem.padding))
html{
字体大小:10px;
}
家长{
字体大小:20px;
}
分区儿童{
边框:1px纯黑;
保证金:5px;
}
#em{
填充:1em;
}
#雷姆{
填充:1rem;
}

1em
1雷姆

由于使用em作为字体大小单位,因此它与直接父元素或声明字体大小的同一元素有关。这里您的
字体大小为2em(即32px),因此行高和边距现在将32px视为其基本值,em将基于此新值进行计算


但是如果您使用rem作为单位,它将始终以body/html字体大小作为其基本值

页边距的
em
值是根据它所应用的元素计算的,在本例中,该元素是计算出的
字体大小为32px的
。使用rem,1rem=16px