font 字体复合写法
基本语法
font: font-style font-weight font-size/line-height font-family;
属性顺序
必须按照以下顺序(用空格分隔):
font-style (可选) - 字体样式font-weight (可选) - 字体粗细font-size (必需) - 字体大小/line-height (可选) - 行高(用 / 分隔)font-family (必需) - 字体类型
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>font 复合写法</title>
<style>
.box {
/*
font-style 和 font-weight 必须写在 font-size 之前
italic 字体倾斜
bold 加粗
20px 表示字体大小
1.5 表示行高是字体大小的1.5倍
"微软雅黑" Arial, 表示字体类型微软雅黑,后备字体 Arial
*/
font: italic bold 20px/1.5 "微软雅黑", Arial;
}
.box2 {
font: 40px/1.5;
/* 任何未指定的值都将设置为其对应的初始值 */
/* font 属性连写时,必须设置 font-size 和 font-family 才能生效 */
}
</style>
</head>
<body>
<div class="box">倾斜加粗文字</div>
</body>
</html>
常用示例
示例1: 完整写法
.text {
font: italic bold 16px/1.5 "微软雅黑", Arial;
}
示例2: 简化写法
.text {
font: 16px "微软雅黑", Arial;
}
示例3: 带行高
.text {
font: 16px/1.5 "微软雅黑", Arial;
}
示例4: 带样式和粗细
.text {
font: italic bold 16px "微软雅黑", Arial;
}
属性值说明
font-style
font-weight
| 值 | 说明 |
|---|
normal | 正常(400) |
bold | 加粗(700) |
100-900 | 数值 |
font-size
font-size: 16px;
font-size: 1em;
font-size: 100%;
line-height
line-height: 1.5;
line-height: 24px;
line-height: 150%;
font-family
font-family: "微软雅黑", Arial, sans-serif;
重要规则
1. 必须包含 font-size 和 font-family
/* 正确 */
.text {
font: 16px "微软雅黑", Arial;
}
/* 错误: 缺少 font-family */
.text {
font: 16px;
}
/* 错误: 缺少 font-size */
.text {
font: "微软雅黑";
}
2. 顺序不能错
/* 正确 */
font: italic bold 16px/1.5 "微软雅黑";
/* 错误: 顺序不对 */
font: 16px italic bold "微软雅黑";
3. 未指定的值重置
/* 先单独设置 */
.text {
font-style: italic;
font-weight: bold;
}
/* 使用 font 复合写法会重置未指定的值 */
.text {
font: 16px/1.5 "微软雅黑"; /* font-style 和 font-weight 被重置为 normal */
}
实际应用
场景1: 正文
body {
font: 14px/1.6 "微软雅黑", Arial, sans-serif;
}
场景2: 标题
h1 {
font: bold 32px/1.2 "微软雅黑", Arial, sans-serif;
}
h2 {
font: bold 28px/1.3 "微软雅黑", Arial, sans-serif;
}
场景3: 按钮文字
.button {
font: 14px "微软雅黑", Arial, sans-serif;
}
场景4: 斜体引用
blockquote {
font: italic 16px/1.6 Georgia, serif;
}
对比
单独设置
.text {
font-style: italic;
font-weight: bold;
font-size: 16px;
line-height: 1.5;
font-family: "微软雅黑", Arial;
}
复合写法
.text {
font: italic bold 16px/1.5 "微软雅黑", Arial;
}
注意事项
- 必需值:
font-size 和 font-family 必须设置 - 顺序: 顺序不能颠倒
- 重置: 未指定的值会被重置
- 分隔:
/ 用于分隔 font-size 和 line-height
学习要点
- 语法:
font: style weight size/height family; - 必需:
font-size 和 font-family 必须设置 - 顺序: 不能颠倒
- 分隔:
/ 分隔大小和行高 - 重置: 未指定的值会被重置为默认