上一篇
html5的字体样式
- 行业动态
- 2025-05-10
- 6
HTML5通过CSS设置字体样式,常用属性包括
font-family
(字体类型)、 font-size
(大小)、 font-weight
(粗细)、 font-style
(斜体/正常),支持像素(px)、em等单位,可定义颜色及加载Web字体(如@font-
HTML5 字体样式详解
基础字体设置
属性 | 说明 | 示例代码 | 效果 |
---|---|---|---|
font-family | 指定字体族,可设置多个备选字体 | p { font-family: "Arial", sans-serif; } | 优先使用 Arial,否则用无衬线字体 |
font-size | 设置字体大小,支持像素(px)、百分比(%)、em/rem 等单位 | h1 { font-size: 24px; } | 标题文字为 24 像素 |
color | 定义文本颜色,支持十六进制、RGB、HSL 等格式 | span { color: #336699; } | 显示蓝绿色文本 |
字体样式属性
属性 | 说明 | 示例代码 | 效果 |
---|---|---|---|
font-weight | 设置字体粗细,范围 100-900(或 normal/bold ) | strong { font-weight: 700; } | 加粗文本 |
font-style | 定义斜体或正常体(italic/normal ) | em { font-style: italic; } | 斜体文本 |
text-transform | 控制文本大小写(uppercase/lowercase/capitalize ) | h2 { text-transform: uppercase; } | |
line-height | 设置行高,影响行间距 | p { line-height: 1.6; } | 6 倍字高的行距 |
外部字体引入
- Google Fonts
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet"> <style> body { font-family: 'Roboto', sans-serif; } </style>
- @font-face 自定义字体
@font-face { font-family: 'MyFont'; src: url('font.woff2') format('woff2'); font-weight: normal; } div { font-family: 'MyFont', serif; }
文本渲染优化
属性 | 说明 | 示例代码 | 效果 |
---|---|---|---|
text-rendering | 控制文本渲染精度(auto/optimizeLegibility/optimizeSpeed ) | p { text-rendering: optimizeLegibility; } | 提升文字清晰度 |
kerning | 调整字符间距(auto/normal/none ) | h3 { kerning: none; } | 关闭字母间距调整 |
text-shadow | 添加文本阴影(水平偏移x 垂直偏移y 模糊半径 颜色) | h1 { text-shadow: 2px 2px 3px #ccc; } | 投影效果 |
兼容性处理
- 浏览器默认字体差异:使用通用字体族(如
sans-serif
)确保跨平台一致。 - 单位选择:优先使用
rem
或 单位适配响应式布局。 - 回退方案:在
@font-face
中声明多种字体格式(如.woff
,.ttf
)。
相关问题与解答
问题1:如何让网页优先使用用户系统中的指定字体?
解答:通过 @font-face
结合本地字体文件,并设置 font-family
优先级。
@font-face { font-family: 'CustomFont'; src: local('SystemFont'), url('fallback.woff2'); } body { font-family: 'CustomFont', sans-serif; }
问题2:为什么设置了 font-size: 16px
但实际显示偏小?
解答:可能受以下因素影响:
- 浏览器默认字体大小被用户修改(需检查根元素
html
的font-size
)。 - 父元素继承了更小的字体尺寸(需重置或逐层调整)。
- 使用了相对单位(如
rem
)但未