font
1. 字体基本属性
1.1 font-family
(字体族)
font-family
指定文本的字体,可使用系统默认字体或自定义 Web 字体。通常建议提供多个字体作为备选,以防首选字体不可用。
1p {
2 font-family: Arial, Helvetica, sans-serif;
3}
Arial
为首选字体;Helvetica
作为备选字体;sans-serif
作为兜底字体(无衬线字体)。
1.2 font-size
(字体大小)
font-size
控制文本大小,可以使用以下单位:
- 绝对单位:
px
(像素)、pt
(点)、cm
、mm
- 相对单位:
em
、rem
、%
、vw
(视口宽度)、vh
(视口高度)
1p {
2 font-size: 16px;
3}
4
5h1 {
6 font-size: 2em; /* 2 倍父级字体大小 */
7}
1.3 font-weight
(字体粗细)
用于设置字体的粗细,通常使用 100
(细)到 900
(粗)之间的值,也可以使用 normal
、bold
等关键字。
1p {
2 font-weight: bold; /* 或者 font-weight: 700; */
3}
1.4 font-style
(字体样式)
控制字体是否倾斜,常用于 italic
或 oblique
。
1p {
2 font-style: italic;
3}
1.5 font-variant
(字体变体)
主要用于小型大写字母(Small Caps)。
1p {
2 font-variant: small-caps;
3}
2. font
复合属性
font
可以一次性定义多个字体相关属性,顺序必须是:
font-style
→ font-variant
→ font-weight
→ font-size/line-height
→ font-family
1p {
2 font: italic small-caps bold 16px/1.5 Arial, sans-serif;
3}
- 斜体 (
italic
)、 - 小型大写 (
small-caps
)、 - 加粗 (
bold
)、 - 字号 (
16px
)、 - 行高 (
1.5
)、 - 字体族 (
Arial, sans-serif
)。
3. 文本渲染相关属性
3.1 line-height
(行高)
调整文本的行间距,一般取 1.4 ~ 1.8
之间的值。
1p {
2 line-height: 1.6;
3}
3.2 letter-spacing
(字母间距)
控制字符之间的间距。
1p {
2 letter-spacing: 2px;
3}
3.3 word-spacing
(单词间距)
调整单词之间的间距。
1p {
2 word-spacing: 5px;
3}
3.4 text-indent
(首行缩进)
设置段落的首行缩进。
1p {
2 text-indent: 2em;
3}
3.5 text-transform
(大小写转换)
uppercase
:转换为大写lowercase
:转换为小写capitalize
:单词首字母大写
1p {
2 text-transform: uppercase;
3}
4. 现代字体特性
4.1 font-feature-settings
(高级 OpenType 特性)
可以控制连字、数字样式等。
1p {
2 font-feature-settings: "liga" 1, "onum" 1;
3}
4.2 font-kerning
(字距调整)
开启或关闭字体的字距调整。
1p {
2 font-kerning: normal;
3}
5. Web 字体
5.1 @font-face
(自定义字体)
可以使用本地或远程字体。
1@font-face {
2 font-family: 'CustomFont';
3 src: url('custom-font.woff2') format('woff2');
4}
5
6p {
7 font-family: 'CustomFont', sans-serif;
8}
5.2 Google Fonts 的使用
可以直接引入 Google Fonts:
1@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
2
3p {
4 font-family: 'Roboto', sans-serif;
5}
6. 响应式字体
6.1 rem
、em
、vw
、vh
1p {
2 font-size: 2vw; /* 视口宽度的 2% */
3}
6.2 clamp()
动态调整字体大小
clamp(min, preferred, max)
让字体在不同屏幕尺寸下动态变化。
1p {
2 font-size: clamp(14px, 2vw, 24px);
3}
7. 字体优化技巧
7.1 字体格式选择
推荐使用 WOFF2(现代浏览器支持),但也可以提供 TTF 和 WOFF 作为备选。
7.2 font-display
(控制字体加载行为)
swap
:使用后备字体,加载后替换fallback
:短暂不可见,再替换optional
:加载慢时不使用
1@font-face {
2 font-family: 'CustomFont';
3 src: url('custom-font.woff2') format('woff2');
4 font-display: swap;
5}
7.3 预加载关键字体
1<link rel="preload" href="custom-font.woff2" as="font" type="font/woff2" crossorigin="anonymous">
总结
- 掌握基本属性(
font-family
、font-size
、font-weight
等) - 使用复合属性 简化代码
- 理解高级特性(
font-feature-settings
、font-kerning
) - 使用 Web 字体 提供更丰富的选择
- 优化字体加载 以提高性能
- 结合响应式技术(
rem
、vw
、clamp()
)确保良好的适配性