字体属性
CSS 字体属性详解
字体属性概述
CSS 中的非布局样式包括多种字体相关属性,用于控制文本的视觉呈现。
常用字体属性
css
p {
font-size: 50px;/* 字体大小 */
line-height: 30px;/* 行高 */
font-family: 幼圆, 黑体; /* 字体栈 */
font-style: italic;/* 斜体 */
font-weight: bold;/* 加粗 */
font-variant: small-caps; /* 小型大写字母 */
}行高特性
- 行高作用于整行而非单个文字
- 未设置高度时,元素高度由内容行高决定
- 文字在行内垂直居中
最佳实践
推荐使用偶数字号和行高,确保垂直居中计算精确
单行文本垂直居中
css
.single-line {
height: 30px;
line-height: 30px; /* 行高=容器高度 */
}多行文本垂直居中
需要计算 padding 值实现
vertical-align 属性
适用于:
- 行内元素 (inline)
- 行内块元素 (inline-block)
- 表格单元格 (table-cell)
css
img {
vertical-align: middle;
}三大核心字体属性
- 字号:
font-size - 行高:
line-height - 字体:
font-family
属性连写格式
css
selector {
font: [weight] [size]/[line-height] [family];
}连写注意事项
必须包含字号和字体才能生效
字体使用规范
- 提供备用字体:
css
font-family: "Microsoft YaHei", "SimSun";- 英文字体优先:
css
font-family: "Times New Roman", "Microsoft YaHei";- 常见中文字体别名:
- 微软雅黑:
Microsoft YaHei - 宋体:
SimSun
行高百分比表示
css
font: 12px/200% "SimSun"; /* 等价于 12px/24px */字体加粗属性
css
.bold-text {
font-weight: bold;/* 700 */
font-weight: normal;/* 400 */
font-weight: 900;/* 最粗 */
}关键总结
- 字体栈应包含备用字体
- 英文和中文字体要正确排序
- 行高影响布局和垂直对齐
- 属性连写需包含必要属性
- 使用偶数字号和行高确保精确对齐
兼容性提示
某些特殊字体需要用户本地安装或使用Web字体方案