17370845950

CSS如何在页面中引入多个字体_使用@font-face定义不同字体族
通过@font-face可定义多个自定义字体族,如CustomTitle和CustomBody,分别用于标题和正文;每个字体族可指定不同字重和样式,浏览器根据font-weight和font-style自动匹配;推荐使用WOFF2格式并设置font-display:swap以优化加载与兼容性,实现丰富且高效的网页排版。

在网页开发中,使用 @font-face 可以引入多个自定义字体,并为每种字体定义独立的字体族(font-family),从而在页面中灵活调用。这种方法让你摆脱系统默认字体的限制,实现更丰富的视觉设计。

定义多个字体族

通过多次使用 @font-face 规则,可以为不同字体文件指定不同的 font-family 名称。浏览器会根据名称加载对应的字体文件。

示例:

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

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

上面代码注册了两个字体族:CustomTitleCustomBody,分别用于标题和正文。

在样式中使用自定义字体

定义好字体族后,可在 CSS 中像使用系统字体一样引用它们。

例如:

h1, h2 {
  font-family: 'CustomTitle', sans-serif;
}

p {
  font-family: 'CustomBody', serif;
}

这样,标题使用 CustomTitle 字体,段落使用 CustomBody,互不干扰。

支持多种字重和样式

如果某字体族包含不同字重(如粗体)或斜体,可分别为其定义 @font-face,并设置对应的 font-weightfont-style

示例:

@font-face {
  font-family: 'CustomBody';
  src: url('fonts/body-bold.woff2') format('woff2');
  font-weight: 700;
  font-style: normal;
}

@font-face {
  font-family: 'CustomBody';
  src: url('fonts/body-italic.woff2') format('woff2');
  font-weight: normal;
  font-style: italic;
}

浏览器会自动匹配正确的字体文件,比如当元素设置 font-weight: 700 时,加载对应粗体版本。

优化加载与兼容性

  • 优先使用 WOFF2 格式,压缩率高,现代浏览器广泛支持。
  • 提供 WOFF 作为降级选项,兼容较老浏览器。
  • 使用 font-display: swap; 避免文字长时间空白(FOIT)。

增强版示例:

@font-face {
  font-family: 'CustomTitle';
  src: url('fonts/title.woff2') format('woff2');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

font-display: swap 表示先显示备用字体,等自定义字体加载完成后再替换,提升用户体验。

基本上就这些。只要为每个字体正确命名并指向对应文件,就能在页面中同时使用多个自定义字体,控制精细,扩展性强。