Size ng Font ng CSS

字体大小

font-size 属性设置文本的大小。

在网页设计中,能够管理文本大小很重要。但是,不应使用调整字体大小来使段落看起来像标题,或是使标题看起来像段落。

请始终使用正确的 HTML 标签,例如 <h1> - <h6> 用于标题,而 <p> 仅用于段落。

font-size 值可以是绝对或相对大小。

绝对尺寸:

  • 将文本设置为指定大小
  • 不允许用户在所有浏览器中更改文本大小(可访问性不佳)
  • 当输出的物理尺寸已知时,绝对尺寸很有用

相对尺寸:

  • 设置相对于周围元素的大小
  • 允许用户在浏览器中更改文本大小

注释:如果您没有指定字体大小,则普通文本(如段落)的默认大小为 16px(16px = 1em)。

以像素设置字体大小

使用像素设置文本大小可以完全控制文本大小:

Example

h1 {
  font-size: 40px;
{}
h2 {
  font-size: 30px;
{}
p {
  font-size: 14px;
{}

Try It Yourself

提示:如果您使用了像素,则仍然可以使用缩放工具来调整整个页面的大小。

用 em 设置字体大小

为了允许用户调整文本大小(在浏览器菜单中),许多开发人员使用 em 而不是像素。

W3C 建议使用 em 尺寸单位。

1em 等于当前字体大小。浏览器中的默认文本大小为 16px。因此,默认大小 1em 为 16px。

可以使用这个公式从像素到 em 来计算大小:pixels/16=em。

Example

h1 {
  font-size: 2.5em; /* 40px/16=2.5em */
{}
h2 {
  font-size: 1.875em; /* 30px/16=1.875em */
{}
p {
  font-size: 0.875em; /* 14px/16=0.875em */
{}

Try It Yourself

在上例中,em 单位的文本大小与上一个例子中的像素大小相同。但是,若使用 em 尺寸,则可以在所有浏览器中调整文本大小。

不幸的是,旧版本的 Internet Explorer 仍然存在问题。放大文本时它比应该大的尺寸更大,缩小文本时会更小。

使用百分比和 Em 的组合

Example

body {
  font-size: 100%;
{}
h1 {
  font-size: 2.5em;
{}
h2 {
  font-size: 1.875em;
{}
p {
  font-size: 0.875em;
{}

Try It Yourself

Our code is currently running well! It displays the same text size in all browsers and allows all browsers to scale or adjust the text size!

Responsive Font Size

You can use vw Unit Setting Text Size, which means "viewport width" ("viewport width").

As a result, the text size will follow the size of the browser window. Please adjust the size of the browser window to see how the font size scales:

Example

<h1 style="font-size:10vw">Hello World</h1>

Try It Yourself

Viewport (Viewport) is the size of the browser window. 1vw = 1% of the viewport width. If the viewport is 50 cm wide, then 1vw is 0.5 cm.