当前位置:首页 > 行业动态 > 正文

html设置字体

在HTML中可通过CSS设置字体,如内联样式 文字或外部样式表定义 .className {font-family: "微软雅黑"}

基础字体设置

属性 说明 示例
font-family 设置字体系列,优先使用指定字体,后续为备选字体 body { font-family: "Arial", sans-serif; }
font-size 定义字体大小,支持像素(px)、百分比(%)、em/rem等单位 h1 { font-size: 24px; }p { font-size: 1rem; }
font-weight 设置字体粗细,范围 100900(或 normal/bold strong { font-weight: 700; }
font-style 定义字体样式(正常、斜体、倾斜) em { font-style: italic; }
text-decoration 添加下划线、删除线等装饰 a { text-decoration: underline; }

字体加载与优化

自定义字体(@font-face)

@font-face {
  font-family: 'CustomFont';
  src: url('fonts/CustomFont.woff2') format('woff2'),
       url('fonts/CustomFont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}
body {
  font-family: 'CustomFont', sans-serif;
}

注意:需确保字体文件路径正确,并处理跨域问题(如启用CORS)。

使用网络字体(如Google Fonts)

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=swap" rel="stylesheet">
<style>
  body {
    font-family: 'Roboto', sans-serif;
  }
</style>

兼容性与细节处理

  1. 多字体兼容
    优先使用系统安全字体(如Arial, sans-serif),避免因字体缺失导致布局错乱。

    p {
      font-family: "Microsoft YaHei", "Heiti SC", sans-serif; / 适配中文环境 /
    }
  2. 移动端适配
    使用rem单位配合根字体声明,便于响应式调整:

    html {
      font-size: 16px; / 1rem = 16px /
    }
    h1 {
      font-size: 2rem; / 32px /
    }
  3. 字体替代方案
    若自定义字体加载失败,可设置通用备选字体:

     font-family: "CustomFont", "Arial", sans-serif;
    }

常见问题与解答

问题1:中文字体显示模糊怎么办?

解答

  • 优先使用系统默认中文字体(如"Microsoft YaHei""PingFang SC")。
  • 若使用自定义字体,确保字体文件清晰度,并调整line-height值(如6)优化排版。
  • 避免过度缩放字体(如小于12px)。

问题2:自定义字体无法加载是什么原因?

解答

  • 路径错误:检查@font-facesrc路径是否准确。
  • 跨域限制:字体文件需允许跨域访问(服务器需配置CORS头)。
  • 格式不支持:优先使用.woff.woff2格式,兼容性更好。
  • 备选方案缺失:未设置通用备选字体时,可能导致字体完全无法显示
0