You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Google Fonts搭配Bootstrap使用时无法正常生效?

问题原因

  • Bootstrap 5内置了全局字体CSS变量--bs-font-sans-serif和默认的字体栈规则,优先级高于你直接给body设置的font-family属性
  • 你将Google字体通过@import写在自定义CSS中,字体加载时序晚于Bootstrap样式,也会导致字体无法正常被调用

解决方案

方案1(推荐):调整字体加载方式和顺序

放弃在自定义CSS中用@import引入Google字体,改为直接在HTML的<head>中引入字体,且放在Bootstrap CSS的加载链接之前:

<head>
    <title>Hello World</title>
    <!-- 优先加载Google字体 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
    <!-- 再加载Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <!-- 最后加载自定义CSS -->
    <link rel="stylesheet" href="style.css">
</head>

修改后删除自定义CSS中原来的@import引入Google字体的代码即可。

方案2:覆盖Bootstrap全局字体变量

如果不想修改HTML的资源加载顺序,直接在自定义CSS的最顶部添加Bootstrap字体变量覆盖规则即可:

/* 放在自定义CSS最顶部 */
:root {
    --bs-font-sans-serif: 'Poppins', sans-serif;
}

/* 原有CSS代码无需修改 */
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');

body {
    margin: 0;
    background: -webkit-gradient(linear, left top, left bottom, from(rgb(168, 168, 168)), to(#464645)) fixed;
    font-family: 'Poppins', sans-serif;
}
header{
    background-color: antiquewhite;
    text-align: center;
    padding: 10px;
}

该方案直接修改Bootstrap依赖的全局字体变量,所有Bootstrap自带的文本样式都会自动继承你设置的Poppins字体,无需额外调整其他样式规则。

内容的提问来源于stack exchange,提问作者Tr0jAn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:54:08