插件窝 干货文章 如何在已有font-family属性下优雅地添加自定义字体?

如何在已有font-family属性下优雅地添加自定义字体?

字体 font 定义 MyCustomFont 436    来源:    2025-03-19

在已有 font-family 属性下优雅地添加自定义字体,可以通过以下步骤实现:

1. 引入自定义字体文件

首先,你需要将自定义字体文件(如 .woff, .woff2, .ttf, .eot 等格式)上传到你的服务器或使用第三方字体托管服务。

2. 使用 @font-face 定义字体

在 CSS 文件中使用 @font-face 规则来定义你的自定义字体。例如:

@font-face {
    font-family: 'MyCustomFont';
    src: url('path/to/MyCustomFont.woff2') format('woff2'),
         url('path/to/MyCustomFont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
    font-display: swap; /* 确保字体加载时不会阻塞页面渲染 */
}

3. 在 font-family 属性中添加自定义字体

在已有的 font-family 属性中,将自定义字体添加到字体栈的最前面。这样,如果用户的浏览器支持自定义字体,它将优先使用自定义字体;如果不支持,则会回退到后续的字体。

body {
    font-family: 'MyCustomFont', 'ExistingFont1', 'ExistingFont2', sans-serif;
}

4. 考虑字体加载性能

为了优化性能,可以使用 font-display: swap; 来确保在自定义字体加载完成之前,浏览器会先显示回退字体。这样可以避免页面加载时的字体闪烁问题。

5. 使用 preload 提前加载字体(可选)

如果你希望自定义字体尽快加载,可以在 HTML 中使用 <link rel="preload"> 来提前加载字体文件:

<link rel="preload" href="path/to/MyCustomFont.woff2" as="font" type="font/woff2" crossorigin>

6. 测试和优化

最后,确保在不同的浏览器和设备上测试你的字体加载效果,并根据需要进行优化。

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Font Example</title>
    <style>
        @font-face {
            font-family: 'MyCustomFont';
            src: url('path/to/MyCustomFont.woff2') format('woff2'),
                 url('path/to/MyCustomFont.woff') format('woff');
            font-weight: normal;
            font-style: normal;
            font-display: swap;
        }

        body {
            font-family: 'MyCustomFont', 'Arial', sans-serif;
        }
    </style>
    <link rel="preload" href="path/to/MyCustomFont.woff2" as="font" type="font/woff2" crossorigin>
</head>
<body>
    <p>This is a paragraph with custom font.</p>
</body>
</html>

通过以上步骤,你可以在已有 font-family 属性下优雅地添加自定义字体,并确保页面的性能和用户体验。