【问题标题】:Why is 1em not based on the defined 16px?为什么1em不是基于定义的16px?
【发布时间】:2018-06-11 13:48:49
【问题描述】:

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

<!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>

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

【问题讨论】:

  • 边距的em 值是根据它所应用的元素计算得出的——在本例中是&lt;p&gt;,计算出的font-size 为32px。
  • 使用 rem,1rem = 16px

标签: css html


【解决方案1】:

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

看看here

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

我想将rem 的“r”视为“根 em”。而根是指html 而不是body 元素。

console.log("padding of div em  : " + window.getComputedStyle(em).padding);
console.log("padding of div rem : " + window.getComputedStyle(rem).padding);
html {
  font-size: 10px;
}
div.parent {
  font-size: 20px;
}
div.child {
  border: 1px solid black;
  margin: 5px;
}
#em {
  padding: 1em;
}
#rem {
  padding: 1rem;
}
<div class="parent">
  <div id="em" class="child">1em</div>
  <div id="rem" class="child">1rem</div>
</div>

【讨论】:

    【解决方案2】:

    由于您使用 em 作为字体大小单位,它相对于直接父元素或声明了 font-size 的相同元素。这里您的&lt;p&gt; 的字体大小为 2em(即 32px),因此行高和边距现在将 32px 作为其基本值,em 正在根据这个新值进行计算。

    但是如果你使用rem作为单位,它总是以body/html字体大小作为它的基值。

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 2016-07-07
      • 2017-01-27
      • 2016-09-16
      • 2015-09-11
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多