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

如何在Bootstrap 5 React项目中使用两种字体并设置独立样式类

为Bootstrap 5 React项目添加第二种字体并设置样式类

步骤1:引入第二种字体

在现有SCSS文件的字体导入代码后,添加第二种Google Fonts的导入语句(以Inter字体为例):

// Import Bootstrap and its default variables
@import '~bootstrap/scss/bootstrap.scss';

// 导入第一种字体
@import url('https://fonts.googleapis.com/css2?family=DM+Serif+Display&display=swap');
// 导入第二种字体(示例为Inter)
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap');

:root{
    --bs-body-font-family:'DM Serif Display', serif;
}

步骤2:新增字体变量(可选但推荐)

在:root中添加第二种字体的CSS变量,方便后续复用:

:root{
    --bs-body-font-family:'DM Serif Display', serif;
    // 新增第二种字体变量
    --font-secondary: 'Inter', sans-serif;
}

步骤3:创建自定义字体样式类

为两种字体分别定义专属样式类,实现局部字体切换:

// 第一种字体的样式类(用于局部强制覆盖)
.font-dm-serif {
    font-family: var(--bs-body-font-family) !important;
}

// 第二种字体的样式类
.font-inter {
    font-family: var(--font-secondary) !important;
}

注:!important用于确保样式优先级高于Bootstrap默认样式,也可以通过提升选择器权重替代。

步骤4:在React组件中使用

直接为元素添加对应类名即可切换字体:

// 使用全局默认字体(无需额外类名)
<p>这是默认的DM Serif Display字体内容</p>

// 使用第二种字体
<p className="font-inter">这是Inter字体的内容</p>

// 为标题单独指定第一种字体
<h2 className="font-dm-serif">DM Serif Display字体的标题</h2>

若项目使用CSS模块,需调整类名引用方式(如styles.fontInter)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:30:43