上一篇
在HTML/CSS中,使用
font-weight属性设置字体粗细,常用值包括:
normal(400)、
bold(700)或100-900的整百数值(数值越大越粗),
font-weight: 600; 或
font-weight: bold;,需确保字体支持对应粗细级别。
在HTML和CSS中设置字体粗细程度主要通过CSS的font-weight属性实现,它直接影响文本的视觉层次和可读性,以下为详细指南:
核心属性:font-weight
作用:控制文本粗细,值范围包括关键字和数值单位:
p {
font-weight: bold; /* 关键字-常用值 */
font-weight: 700; /* 数值-推荐方式 */
}
属性值详解
-
关键字值(共9种):
normal:默认值(等效于400)bold:加粗(等效于700)lighter:比父元素更细bolder:比父元素更粗- 其他相对值:
thin/extra-light/light/medium/semi-bold/extra-bold/black
注:部分关键字需字体文件支持
-
数值值(推荐使用):
- 范围:
100~900(整百递进) - 常用值:
400= normal700= bold
- 示例:
font-weight: 600;(中等加粗)
- 范围:
实际应用场景
- 全局基础设置:
body { font-weight: 400; /* 默认正常粗细 */ } ```加粗**: ```css h1 { font-weight: 700; /* 强视觉层次 */ } - 特定元素强调:
.important { font-weight: 800; /* 超粗强调 */ }
常见问题与解决方案
-
字体不支持指定字重:
- 现象:设置
font-weight: 300;但渲染为默认粗细 - 解决:
@font-face { font-family: "CustomFont"; src: url("light.woff2") format("woff2"); font-weight: 300; /* 明确定义字重 */ } body { font-family: "CustomFont", sans-serif; font-weight: 300; /* 启用轻量字重 */ }
- 现象:设置
-
bolder/lighter不生效:- 原因:父元素未明确定义字重
- 修正:
.parent { font-weight: 400; /* 明确父元素字重 */ } .child { font-weight: bolder; /* 此时生效为700 */ }
最佳实践
- 优先使用数值:避免
bold等关键字的浏览器差异 - 字体家族兼容:
font-family: "Helvetica Neue", Arial, sans-serif; /* 备选通用字体 */
- 响应式适配:
@media (max-width: 768px) { h1 { font-weight: 600; /* 小屏幕降低加粗程度 */ } } - 可访问性:
- WCAG标准建议:正文文本字重不低于
400 - 避免超细字体(
<300)用于长文本
- WCAG标准建议:正文文本字重不低于
浏览器支持说明
- 所有现代浏览器均支持
font-weight - IE8+支持数值单位,IE7需使用关键字
- 移动端兼容性:Android 4.4+ / iOS 5.1+ 全支持
引用说明参考MDN Web文档关于font-weight的权威指南,遵循W3C CSS Fonts Module Level 4规范,并结合WebAIM可访问性实践建议。
