font-size 字体大小
基本语法
font-size: 长度值;常用单位
1. px - 像素(绝对单位)
font-size: 16px;
font-size: 24px;
font-size: 32px;特点:
- 固定大小,不会随浏览器设置变化
- 最常用的单位
2. % - 百分比(相对单位)
font-size: 100%; /* 相对于父元素字体大小 */
font-size: 200%; /* 父元素的两倍 */
font-size: 150%; /* 父元素的1.5倍 */示例:
<style>
body {
font-size: 16px; /* 浏览器默认大小 */
}
.box {
font-size: 200%; /* 16px × 2 = 32px */
}
</style>
<body>
<div class="box">字体大小为 32px</div>
</body>3. em - 相对单位
font-size: 1em; /* 父元素的1倍 */
font-size: 2em; /* 父元素的2倍 */
font-size: 1.5em; /* 父元素的1.5倍 */示例:
<style>
body {
font-size: 16px;
}
.box {
font-size: 2em; /* 16px × 2 = 32px */
}
</style>
<body>
<div class="box">字体大小为 32px</div>
</body>4. rem - 根元素相对单位
font-size: 1rem; /* 根元素的1倍 */
font-size: 2rem; /* 根元素的2倍 */特点: 相对于 <html> 元素的字体大小
5. 关键字
font-size: xx-small; /* 最小 */
font-size: x-small;
font-size: small;
font-size: medium; /* 默认值,相当于16px */
font-size: large;
font-size: x-large;
font-size: xx-large; /* 最大 */示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>font-size 字体大小</title>
<style>
.box {
/* 第一种: px */
font-size: 40px;
}
.box2 {
/* 百分比,相对于父元素 */
font-size: 200%; /* 浏览器默认16px × 2 = 32px */
}
.box3 {
/* em 也是相对单位,相对于父元素 */
font-size: 2em; /* 16px × 2 = 32px */
}
</style>
</head>
<body>
<div class="box">font-size控制字体大小 (40px)</div>
<div class="box2">百分比方式 (32px)</div>
<div class="box3">em方式 (32px)</div>
</body>
</html>单位对比
| 单位 | 类型 | 基准 | 用途 |
|---|---|---|---|
px | 绝对单位 | 像素 | 精确控制,推荐 |
% | 相对单位 | 父元素 | 相对父元素 |
em | 相对单位 | 父元素 | 响应式布局 |
rem | 相对单位 | 根元素 | 现代布局,推荐 |
实际应用
场景1: 响应式字体
html {
font-size: 16px;
}
/* 移动端 */
@media (max-width: 768px) {
html {
font-size: 14px;
}
}
/* 使用 rem */
h1 {
font-size: 2rem; /* 桌面端: 32px, 移动端: 28px */
}
p {
font-size: 1rem; /* 桌面端: 16px, 移动端: 14px */
}场景2: 标题字体大小
h1 { font-size: 32px; }
h2 { font-size: 28px; }
h3 { font-size: 24px; }
h4 { font-size: 20px; }
h5 { font-size: 16px; }
h6 { font-size: 14px; }场景3: 辅助文字
/* 小字 */
.small-text {
font-size: 12px;
}
/* 大字 */
.large-text {
font-size: 20px;
}
/* 强调文字 */
.highlight {
font-size: 18px;
font-weight: bold;
}最佳实践
1. 使用 px 或 rem
/* 推荐: px - 简单直接 */
body {
font-size: 16px;
}
/* 推荐: rem - 响应式 */
body {
font-size: 1rem;
}
/* 不推荐: % 和 em 容易造成嵌套问题 */2. 设置基准字体
html {
font-size: 16px; /* 设置根元素字体大小 */
}
body {
font-size: 1rem; /* 使用 rem */
}3. 避免过小或过大
/* 最小不小于 12px,避免难以阅读 */
.text-smallest {
font-size: 12px;
}
/* 最大不超过 36px,避免过大 */
.text-largest {
font-size: 36px;
}学习要点
- 推荐单位:
px(简单) 或rem(响应式) - px: 绝对单位,固定大小
- %: 相对单位,相对于父元素
- em: 相对单位,相对于父元素
- rem: 相对单位,相对于根元素
- 浏览器默认: 16px
- 响应式: 使用 rem + 媒体查询