使用 em 设置 h1 大小时大小错误

Wrong size when setting size for h1 using em

我有 h1 标签,我尝试使用 em 设置此标签的字体大小,但它没有变大,而是变小了。下面是我的代码:

h1{
  font-size: 1.2em;
}
<div class="container">
  <h1>This is a title</h1>
  <p>hello this is a paragraph</p>
  </div>

正如我在代码中注意到的那样,删除 1.2em 后,它又变大了。根据我的理解,1em = 页面的当前字体大小。制作 2em 应该使它的大小加倍。 1.2em 应该让它变大一点,但对我来说它变小了。在这种情况下 em 是如何工作的?

你的定义是正确的,但也有默认样式,em与固定大小的父元素的字体大小有关(或body 元素(如果没有其他元素具有固定大小)。

这是一个例子:

body {
  font-size: 13px;
}
.container h1{
  font-size: 1.2em;
}
.container2 {
  font-size: 20px;
}
.container3 {
  font-size: 0.5em;
}
<div>text - 13px</div>
<h1>title 1 - 26px (default to 2em == 13*2 = 26px)</h1>
<div class="container">
  <h1>This is a title - 15.6px (1.2em == 13*1.2 = 15.6px)</h1>
  <p>hello this is a paragraph - 13px</p>
</div>
<div class="container2">
  <h1>Another title - 40px (parent is 20px, default is 2em, 2*20 == 40px)</h1>
</div>
<div class="container3">
  <h1>3rd title - 13px (parent is 13px*0.5(em) == 6.5, default h1 is 2em, 2*6.5px == 13px)</h1>
</div>

From MDN:

Ems Another way of setting the font size is with em values. The size of an em value is dynamic. When defining the font-size property, an em is equal to the size of the font that applies to the parent of the element in question. If you haven't set the font size anywhere on the page, then it is the browser default, which is often 16px. So, by default 1em = 16px, and 2em = 32px. If you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px. Note that the value 2 is essentially a multiplier of the current em size.

默认情况下,页面 em16px - 因此 1.2em 等于 19px

页面的默认 h12em 或等于 32px

因此,通过更改现有值,它会减小 h1 的自然大小。

From my understanding, 1em = the current font size of the page

事实并非如此。您将 emrem 混淆了,后者是根元素的计算 font-size

em 是使用它的元素的计算 font-size

但是,当您在 font-size 本身上使用 em 单位时,这当然是行不通的,那将是一个循环定义。在这种情况下,em 指的是父元素的计算 font-size

然后,如果 h1 在用户代理样式表中默认使用 font-size: 2em 设置样式,如果您使用 font-size: 1.2em 覆盖它,它将变得更小!