上一篇
html语言改字体
- 行业动态
- 2025-04-25
- 3
HTML改字体用CSS设置font-family属性,推荐外部或内部样式表定义
使用CSS设置字体
在HTML中修改字体主要通过CSS(层叠样式表)实现,以下是常用方法及示例:
内联样式(直接在标签中设置)
<p style="font-family: 'Arial'; font-size: 16px; color: #333;"> 这段文字使用Arial字体,16px大小,深灰色 </p>
内部样式表(在<head>
中定义)
<head> <style> .custom-text { font-family: 'Microsoft YaHei', sans-serif; font-size: 18px; color: darkblue; font-weight: bold; } </style> </head> <body> <span class="custom-text">自定义样式文本</span> </body>
外部样式表(链接CSS文件)
<!-HTML文件 --> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <h1 class="title">外部样式标题</h1> </body> <!-styles.css文件 -->{ font-family: 'Georgia', Times, serif; font-size: 24px; color: #8B0000; letter-spacing: 2px; }
字体属性说明表
属性名 | 功能描述 | 示例值 |
---|---|---|
font-family | 设置字体系列(优先使用首个可用字体) | 'Arial', sans-serif |
font-size | 设置字体大小 | 16px / 2em / large |
font-weight | 设置字体粗细 | bold / 700 |
color | 设置字体颜色 | #333 / rgb(51,51,51) |
text-transform | 文本转换(大写/小写) | uppercase / lowercase |
text-decoration | 文本装饰(下划线/删除线) | underline / line-through |
line-height | 行高 | 5 / 20px |
font-style | 字体样式(斜体/正常) | italic / normal |
特殊字体加载方案
使用Google Fonts
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet"> <body> <p style="font-family: 'Roboto', sans-serif;">Google Web字体示例</p> </body>
使用@font-face加载本地字体
@font-face { font-family: 'MyCustomFont'; src: url('fonts/myfont.woff2') format('woff2'), url('fonts/myfont.ttf') format('truetype'); } .custom-font { font-family: 'MyCustomFont', sans-serif; }
常见问题与解答
Q1:如何让中文显示为宋体,英文显示为Arial?
A:通过设置多个备选字体,利用字体族特性实现:
body { font-family: "SimSun", "宋体", Arial, sans-serif; }
系统会优先使用宋体显示中文,若无则回退到Arial显示英文。
Q2:为什么设置了字体但页面没有变化?
A:可能原因及解决方案:
- 字体名称错误:检查拼写是否准确(如
'Arial'
不能写成Arial
) - 字体未加载:网络字体需等待加载完成,可添加
&display=swap
参数加速 - 优先级问题:检查是否有其他样式覆盖,可使用
!important
提高优先级 - 字体兼容性:部分生僻字体需@font-face引入,或选择通用安全