html怎样修改字体
- 行业动态
- 2025-05-06
- 2303
设置字体类型
HTML本身无法直接定义字体,需通过CSS的font-family
属性实现,可设置多个备选字体,若首选字体不可用则自动替换。
示例代码:
<p style="font-family: 'Arial', sans-serif;">这是一段文本</p>
常用字体分类:
| 类别 | 示例字体 |
|—————|————————–|
| 通用族名称 | serif
(宋体)、sans-serif
(无衬线)、monospace
(等宽) |
| 具体字体名称 | Arial
、Times New Roman
、Microsoft YaHei
|
| 中文推荐 | SimSun
(宋体)、SimHei
(黑体)、Microsoft YaHei
(微软雅黑) |
调整字体大小
通过font-size
属性设置,单位可用px
(像素)、em
(相对倍数)、rem
(根元素倍数)等。
示例代码:
<p style="font-size: 16px;">16像素文本</p> <p style="font-size: 1.5em;">父元素1.5倍大小</p>
单位对比:
| 单位 | 说明 |
|———|————————–|
| px
| 固定大小,不受缩放影响 |
| em
| 相对于父元素字体大小 |
| rem
| 相对于根元素(<html>
)字体大小 |
修改字体颜色
使用color
属性设置文本颜色,支持颜色名称、十六进制、RGB等格式。
示例代码:
<p style="color: #336699;">蓝色文本</p> <p style="color: rgb(255,0,0);">红色文本</p>
颜色表示法:
| 格式 | 示例 |
|—————|——————–|
| 颜色名称 | red
、blue
|
| 十六进制 | #FF0000
(红) |
| RGB函数 | rgb(255,0,0)
|
| RGBA函数 | rgba(255,0,0,0.5)
(半透明红) |
设置字体粗细
通过font-weight
调整粗细,数值范围100
(最细)到900
(最粗),或使用关键词bold
/normal
。
示例代码:
<p style="font-weight: bold;">加粗文本</p> <p style="font-weight: 300;">较细文本</p>
引入自定义字体
使用@font-face
或外部链接(如Google Fonts)添加特殊字体。
@font-face 示例:
@font-face { font-family: 'MyFont'; src: url('fonts/myfont.woff2') format('woff2'); } body { font-family: 'MyFont', sans-serif; }
Google Fonts 示例:
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=swap" rel="stylesheet"> <p style="font-family: 'Roboto', sans-serif;">Google Fonts文本</p>
综合案例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8">字体样式示例</title> <style> body { font-family: 'Microsoft YaHei', sans-serif; / 全局字体 / font-size: 16px; / 全局大小 / } .highlight { color: #FF6600; / 橙色 / font-weight: bold; / 加粗 / font-size: 1.2em; / 放大1.2倍 / } </style> </head> <body> <p>普通文本</p> <p class="highlight">高亮文本</p> </body> </html>
相关问题与解答
问题1:如何让整个网页统一使用某种字体?
解答:
在<body>
或全局CSS中设置font-family
,
body { font-family: 'Arial', sans-serif; / 优先使用Arial,否则用无衬线字体 / }
若需强制所有元素继承此字体,可在根元素<html>
上设置:
html { font-family: 'Arial', sans-serif; }
问题2:为什么引入的自定义字体没有显示?
解答:
- 路径错误:检查
@font-face
中src
路径是否正确,建议使用相对路径或绝对URL。 - 格式不支持:确保字体文件格式(如
.woff2
、.ttf
)被浏览器兼容。 - 跨域问题:若字体文件存放在服务器,需配置CORS头允许跨域访问。
- 优先级问题:如果未指定备选字体,且主字体加载失败,可能显示