关于html:设置body标签的字体大小

Setting the font-size of a body tag

我一直在尝试配置一个基本的CSS模板,可以用来开始使用REM。我看到了设置以下body { font-size: 62.5% };的方法,以便于数学计算(1rem = 10px,因为16px是默认字体大小)。

我不确定我是否喜欢这种方式,因为如果10px的字体大小不是我的基线,则必须指定-

以及

标签的大小。

我一直在尝试一些不同的方法,并且对px%在字体大小方面的关系非常困惑。请看以下示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>

<body>

  <header>
    Testing h1
    Testing h2
  </header>

  <main>
    <p>
Random paragraph
</p>
  </main>
</body>

</html>

考虑以下css:

1
2
3
body {
 font-size: 100%;
}

我希望浏览器将字体显示为其默认大小,即16px。

标记中的所有内容仍为16px,但是-

还原为浏览器样式表中指定的原始大小。为什么未将所有文本设置为16px?

另一个例子:

1
2
3
body {
  font-size: 12px;
}

为什么-

不采用12px的这种字体大小? -

确实变小了(12/16 = 0.75降低了75%)。我希望h1为12px或保持相同的默认值,因为在用户代理样式表中为h1-h6指定的值是特定于更多的。

规则在指定百分比方面如何工作?设置样式表以便可以使用REM的最佳实践是什么?


h1的默认font-size设置为2em,表示2 x the font size of the parent element。与其他标题相同,它们都具有使用em单位指定的font-size

enter image description here

font-size使用百分比还相对于父级font-size,并且表示p x the font size of the parent element,其中p0(对于0%)和1(对于100%)之间的值。

因此,如果在主体中指定100%,则主体将具有16px(默认为font-size),而h1将具有32px

您可以使用相同的逻辑为其他标题找到font-size

1
2
3
body {
  font-size:100%;
}
1
this a text

如果在正文中指定12px,则h1将具有24px

1
2
3
body {
  font-size:12px;
}
1
this a text

并且指定62.5%将使主体具有10pxh1 20px

1
2
3
body {
  font-size:62.5%;
}
1
this a text

而且,由于p没有font-size的默认值,它将仅继承主体中指定的值。

您可以使用开发工具轻松地在"计算"选项卡中检查这些值:

enter image description here

从文档中:

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

对于百分比:

A positive value, relative to the parent element's font size.


Why doesn't -

take this font size of 12px?

当您更改其祖先的字体大小时,和相关元素不会将其字体大小更改为与祖先相同,这仅仅是因为其默认字体大小(在浏览器内置的样式表中)未设置为100%1eminherit或类似名称,并且您没有指定其他字体大小来覆盖浏览器提供的字体大小。

-

does get smaller (by 75% as 12/16 = 0.75). I'd expect h1 to be either 12px or stay the same default value because the value specified for h1-h6 in the user agent stylesheets is MORE specific.

在浏览器样式表中指定的值(至少在我的浏览器中)使用em单位,因此它与父元素的字体大小成比例(在情况下为两倍)。

How do the rules work in terms of specifying percentages?

用于祖先元素(px%或其他任何东西)的字体大小的单位选择无关紧要。


rem相对于HTML,而不是BODY

rem单位基于HTML元素而不是BODY元素的字体大小。因此,您应该这样设置基本字体大小:

1
HTML {font-size: 62.5%; } /* Now `rem` is equivalent to `10px` */

代替

1
BODY {font-size: 62.5%; } /* Does NOT affect `rem` */

HTML字体大小可能会影响滚动速度

请注意,至少在某些浏览器中,HTML元素的字体大小会影响滚轮滚动步长:HTML元素的字体大小越小,步长越小,滚动速度就越慢。

重置所有元素的字体大小

要重置所有元素的字体大小,可以使用通用选择器:

1
* {font-size: 100%; }

要么:

1
* {font-size: 1em; }

正确的DOCTYPE可确保跨浏览器的一致性

另外,请确保在HTML文档的开头具有正确的DOCTYPE声明,以为该文档打开标准兼容模式,以实现一致的跨浏览器呈现和行为:

1
<!DOCTYPE html>

在我这边工作得很好。唯一的可能是,您的HTML中缺少指向CSS文件的链接... :)
否则,只是为了确保对同一属性尝试内联样式。