上一篇
html将字体样式
- 行业动态
- 2025-05-11
- 8
HTML字体样式通过CSS设置,如font-family、size等属性,可内联、内部或外部样式表
使用HTML标签属性设置字体样式
HTML早期可通过标签属性直接设置字体样式,
<font>
标签(已废弃):<font face="Arial" size="4" color="red">文字</font>
缺点:不符合现代HTML标准,建议使用CSS替代。
属性 | 说明 | 示例效果 |
---|---|---|
face | 设置字体名称 | Arial , Times New Roman |
size | 设置字体大小(1~7) | size="3" (较小) |
color | 设置字体颜色 | color="blue" |
使用CSS设置字体样式
CSS是现代网页设计的标准方式,通过样式规则控制字体。
内联样式(直接写在标签中)
<span style="font-family: 'Arial'; font-size: 16px; color: #333;">文字</span>
内部样式表(写在<style>
标签中)
<style> .custom-text { font-family: 'Helvetica', sans-serif; font-size: 18px; font-weight: bold; color: #0066cc; } </style> <p class="custom-text">文字</p>
外部样式表(单独CSS文件)
/ styles.css / body { font-family: '宋体', serif; font-size: 14px; }
<link rel="stylesheet" href="styles.css">
CSS属性 | 说明 | 示例值 |
---|---|---|
font-family | 设置字体族(可多级备选) | 'Arial', sans-serif |
font-size | 设置字体大小 | 16px , 2em |
font-weight | 设置字体粗细 | bold , 400 |
color | 设置字体颜色 | #ff0000 , rgba(0,0,0,0.8) |
line-height | 设置行高 | 5 , 20px |
text-transform | 文本大小写转换 | uppercase , capitalize |
引入外部字体(如Google Fonts)
通过@import
或<link>
引入外部字体库,
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> <style> body { font-family: 'Roboto', sans-serif; } </style>
说明:
family=Roboto
:选择字体名称。display=swap
:优化字体加载(避免FOIT问题)。
字体加载与性能优化
- FOIT(Flash of Invisible Text):字体未加载完成前文字不可见。
- FOTC(Flash of Unstyled Text):字体未加载完成前显示默认样式。
解决方法:
- 使用
font-display: swap
(Google Fonts支持)。 - 预加载字体:
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" as="style">
问题与解答
问题1:CSS中如何设置字体样式的优先级?
答:CSS优先级遵循以下规则:
- 内联样式(
style
属性) > 内部/外部样式表。 - 后定义的样式覆盖先定义的样式。
- 使用
!important
强制覆盖(需谨慎)。
问题2:引入外部字体后,网页打开速度变慢怎么办?
答:
- 使用
display=swap
让文本快速可见。 - 限制字体种类,优先使用系统安全字体。
- 通过
preload
预