html字体样式名
- 行业动态
- 2025-05-07
- 6
HTML常用字体样式属性包括
font-family
(字体族)、 font-size
(字号)、 font-weight
(粗细)、 font-style
(样式), font-family:"Arial", sans-serif; font-size:16px; font-weight:bold; font-style:italic;
可定义
HTML字体样式核心属性
font-family
用于定义字体类型,可指定多个备选字体,若首选字体未安装,浏览器会按顺序选择备选字体。
语法:font-family: "字体名称1", "字体名称2", generic-family;
示例:
p { font-family: "Arial", "Helvetica", sans-serif; }
font-size
设置字体大小,支持多种单位。
| 单位 | 说明 | 示例 |
|————–|————————–|———————|
| px | 绝对像素(固定大小) | 16px
|
| em/rem | 相对单位(基于父元素/根元素) | 5em
或 5rem
|
| % | 百分比(基于父元素) | 120%
|
| 关键字 | 预定义尺寸(如 larger
) | xx-small
|
font-weight
定义字体粗细,范围为100~900(400=正常,700=加粗)。
示例:
h1 { font-weight: bold; / 等同于 700 / }
font-style
设置字体样式,如斜体或倾斜。
常见值:
normal
(正常)italic
(斜体)oblique
(倾斜,需角度参数,如oblique 20deg
)
复合属性:font
可一次性声明字体的多个属性,顺序为:font-weight
→ font-size
→ line-height
→ font-family
。
示例:
body { font: bold 16px/1.5 "Arial", sans-serif; }
自定义字体加载(@font-face)
通过 @font-face
引入自定义字体文件。
语法:
@font-face { font-family: "MyFont"; src: url("myfont.woff2") format("woff2"), url("myfont.woff") format("woff"); }
使用:
.text { font-family: "MyFont", sans-serif; }
注意事项
- 字体兼容性:优先使用系统安全字体(如 Arial、Times New Roman),避免因字体缺失导致布局错乱。
- 单位选择:响应式设计推荐使用
rem
或em
,避免固定像素(px
)导致移动端适配问题。 - 性能优化:自定义字体需压缩文件(如
.woff2
),并通过format()
声明格式。
相关问题与解答
问题1:如何让中文和英文分别显示不同字体?
解答:通过 font-family
结合 Unicode 范围分段设置。
body { font-family: "Microsoft YaHei", sans-serif; / 中文默认 / } .english { font-family: "Arial", sans-serif; / 仅英文生效 / }
问题2:为什么自定义字体在部分浏览器无法显示?
解答:可能原因:
- 字体文件路径错误或格式不兼容(需提供
.woff
/.woff2
/.ttf
等多种格式)。 - 未声明
font-family
或权重冲突。 - 跨域问题(需配置服务器