CSS 字体
学习 font-family/size/weight · 难度:入门 · +10XP
CSS 字体属性详解
字体是网页设计中最重要的元素之一。CSS 提供了多种属性来控制网页中文字的字体、大小、粗细和样式,帮助打造独特的视觉风格。
字体族 font-family
font-family 指定元素的字体。建议设置多个字体名称作为"后备"机制,如果浏览器不支持第一个字体,就会尝试下一个。
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
h1 {
font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
}
code {
font-family: "Fira Code", "Consolas", monospace;
}
字体大小 font-size
font-size 设置文字的大小。可以使用像素(px)、em、rem、百分比等单位。推荐使用 rem 作为主要字体大小单位,因为它相对于根元素,易于全局调整。
html {
font-size: 16px; /* 基准大小 */
}
body {
font-size: 1rem; /* 16px */
}
h1 {
font-size: 2rem; /* 32px */
}
p {
font-size: 0.875rem; /* 14px */
}
字体粗细 font-weight
font-weight 定义字体的粗细程度。常用值有:normal(400)、bold(700)、lighter、bolder,以及 100 到 900 的数字值。
h1 {
font-weight: 700; /* 粗体 */
}
p.light {
font-weight: 300; /* 细体 */
}
span.medium {
font-weight: 500; /* 中等 */
}
字体样式 font-style
font-style 主要用于设置斜体文字。
em {
font-style: italic;
}
cite {
font-style: oblique; /* 倾斜(类似斜体但略有不同) */
}
p {
font-style: normal; /* 默认,非斜体 */
}
字体简写 font
font 是一个简写属性,可以在一行中设置多个字体属性。顺序必须是:font-style font-variant font-weight font-size/line-height font-family。
p {
font: italic small-caps bold 16px/1.5 "Microsoft YaHei", sans-serif;
}
/* 最少需要 font-size 和 font-family */
h1 {
font: 2rem "PingFang SC", sans-serif;
}
自定义字体 @font-face
使用 @font-face 规则可以加载自定义字体文件,让网页使用不在用户电脑上的字体。
@font-face {
font-family: "MyFont";
src: url("/fonts/MyFont.woff2") format("woff2"),
url("/fonts/MyFont.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap; /* 先用系统字体,加载完再替换 */
}
h1 {
font-family: "MyFont", sans-serif;
}
字体属性速查表
| 属性 | 作用 | 常用值 | 示例 |
|---|---|---|---|
| font-family | 字体族 | 字体名称列表 | font-family: Arial, sans-serif; |
| font-size | 字体大小 | px/em/rem/% | font-size: 16px; |
| font-weight | 字体粗细 | 100-900 / normal / bold | font-weight: 700; |
| font-style | 字体样式 | normal/italic/oblique | font-style: italic; |
| font-variant | 小型大写字母 | normal/small-caps | font-variant: small-caps; |
| line-height | 行高 | 数字/px/em/% | line-height: 1.5; |
| font-display | 字体加载策略 | auto/swap/block/fallback/optional | font-display: swap; |
???? 练习
- 为网页设置一套完整的中文字体栈,包含 PingFang SC、Microsoft YaHei 和系统默认字体
- 使用 rem 单位设置 h1 到 h6 的层级字号梯度
- 使用 @font-face 从 Google Fonts 下载一个英文字体并在页面中使用
- 尝试用 font 简写属性一次性设置多个字体属性
- 对比 normal、italic 和 oblique 三种 font-style 的视觉效果