使用 em 单位时字体大小不正确

font size incorrect on using em unit

我的代码的默认 font-size 等同于 10px0.625em。因此,根据这条规则,要将 <p> 的字体大小设置为 7px,我可以使用 0.7em。但在我的例子中,即使我将 <p> 的字体大小减小为 0.5em 或更小,浏览器也会采用 9px 的固定字体大小(在浏览器的 "computed" 部分中选中) .

body {
  font-size: 0.625em;
}

h1 {
  font-size: 2.5em; 
}

h2 {
  font-size: 1.875em; 
}

p {
  font-size: 0.7em; 
}
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>This is a paragraph.</p>
<p>Specifying the font-size in em allows all major browsers to resize the text.
Unfortunately, there is still a problem with older versions of IE. When resizing the text, it becomes larger/smaller than it should.</p>

如果您希望字体大小与根字体大小严格相关(在 html 的规则中设置,而不是 body,应该在 px 中) ,您必须使用 rem 单位或百分比,但不能使用 em(这将与特定元素或其父元素的默认浏览器大小相关)

另外,大多数浏览器都有一个 "minimum font display" 设置来防止小尺寸变得不可读。这很可能在您的浏览器中设置为 9px。

如你所说p 的字体大小为 7px 我可以使用 0.7em,这是不正确的,因为这里是你的默认字体大小是16px。如果

10px == 0.625em then
7px = (0.625/10)*7em = 0.4375em

如果您使用 10px 作为默认字体,则必须设置 body html 字体大小 px10px

html,
body {
  font-size: 10px;
}

检查下面的代码片段

html{
  font-size: 10px;
}

h1 {
  font-size: 2.5em;
}

h2 {
  font-size: 1.875em;
}

p {
  font-size: 0.7em;
}
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>This is a paragraph.</p>
<p>Specifying the font-size in em allows all major browsers to resize the text. Unfortunately, there is still a problem with older versions of IE. When resizing the text, it becomes larger/smaller than it should.</p>

不能设置

body {
  font-size: 0.625em;
}

您需要将 10px 设置为 body font-size。 然后使用 em,计算将按照您的预期进行。否则它将采用浏览器设置的默认 font-size

body {
  font-size: 10px;
}

h1 {
  font-size: 2.5em; 
}

h2 {
  font-size: 1.875em; 
}

p {
  font-size: 0.7em; 
}
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>This is a paragraph.</p>
<p>Specifying the font-size in em allows all major browsers to resize the text.
Unfortunately, there is still a problem with older versions of IE. When resizing the text, it becomes larger/smaller than it should.</p>

详细了解如何设置 em font-sizes here