CSS font-size 属性调整网页上的文本大小。例如,

p {

font-size: 36px;

}

浏览器输出

这里,font-size: 36px 将 p 元素的字体大小设置为 36px。

CSS 字体大小语法

font-size 属性具有以下语法:

font-size: predefined keyword|length|initial|inherit;

这里,

预定义关键词:指具有预定 font-size 的关键词,如 small、medium、large 等。

长度:指使用特定长度单位(如 px、em 或点)的 font-size,例如 24px、2em 等。

font-size 的可能值如下:

描述

xx-small

显示极小文本大小

x-small

显示特小文本大小

small

显示小文本大小

medium

显示中等文本大小

large

显示大文本大小

x-large

显示特大文本大小

xx-large

显示极大文本大小

xx-small

显示极小文本大小

x-small

显示特小文本大小

smaller

显示相对较小的文本大小

larger

显示相对较大的文本大小

initial

将字体大小设置为默认值

inherit

从父元素继承字体大小

绝对值和相对值

CSS 字体大小可以指定为:

绝对值

相对值

1. 使用绝对值的字体大小

绝对值将大小设置为固定的指定值。它们以特定的长度值指定,例如像素 (px)、点 (pt) 等。例如,

HTML

CSS

Using absolute length units

font size of 24 points

font size of 16 pixels

font size of 10 millimeters

p.first_paragraph {

/* sets the font size to 24 points */

font-size: 24pt;

}

p.second_paragraph {

/* sets the font size to 16 pixels */

font-size: 16px;

}

p.third_paragraph {

/* sets the font size to 10 millimeters */

font-size: 10mm;

}

浏览器输出

注意:像素 (px) 通常用作网页上字体大小的绝对单位。像素提供了一种一致而精确的方式来指定字体大小,不受用户偏好或设备分辨率的影响。

2. 使用相对值的字体大小

相对值将大小设置为相对于其父元素。

相对值使用关键词和百分比值指定。例如,

HTML

CSS

Using em

Normal heading

Heading with em

This is some example text.

div {

font-size: 20px;

}

div h1 {

font-size: 1.25em;

}

浏览器输出

在上面的示例中,我们有两个

元素,一个在
元素之外,另一个在
元素之内。第一个

元素具有默认大小,而第二个

元素具有 1.25em 的 font-size,它相对于其父元素
的 font-size。

的 font-size 为 20px,因此

的 font-size 将是 20px 的 1.25 倍,即 25px。

常见问题使用 rem 的字体大小虽然 em 基于父元素的 font-size,但 rem 基于根元素 html 中设置的 font-size。例如,

HTML

CSS

Using rem

Example heading

This is some example text.

html {

/*set the font size to 18px,

default would be 16px */

font-size: 18px;

}

h1 {

/*sets font-size to 2 * 18px = 36px*/

font-size: 2rem;

}

p {

/* sets font-size to 18px */

font-size: 1rem;

}

浏览器输出

使用百分比的字体大小

HTML

CSS

Using percentage

Relative font size

Example Heading

This is some example text.

/*sets div font size to 20px */

.div {

font-size: 20px;

}

/*sets h1 font size to 120% */

div h1 {

font-size: 120%;

}

浏览器输出

在上面的示例中,第一个

元素的 font-size 没有明确设置,因此它使用默认大小。

第二个

元素的 font-size 为 120%,相对于其父元素。父元素
的 font-size 为 20px,因此第二个

元素的字体大小将是 20px 的 120%,即 24px。