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

如何在Bootstrap 5.3中用CSS样式表覆盖默认字体粗细

问题:Bootstrap 5.3中如何覆盖h1默认字重为900?

我需要让h1标题使用Montserrat字体、字重900,但通过开发者工具发现我的CSS被Bootstrap 5.3的样式覆盖——字重被改成500,行高变为1.2。我不能删除Bootstrap的链接,否则导航栏会失效。之前试过Bootstrap 4的Sass文件覆盖方案,但在5.3版本里无效,目前找不到适配5.3的方法。

现有代码示例

CSS代码:

h1 {
  font-family: 'Montserrat', sans-serif;
  line-height: 1.5; /* 被覆盖为1.2 */
  font-size: 3rem;
  font-weight: 900; /* 被覆盖为500 */
}

HTML代码:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">

<h1>Montserrat black 900 font weight</h1>
解决方案

以下是几种适配Bootstrap 5.3的有效覆盖方法:

1. 提高选择器优先级

Bootstrap 5.3对h1的样式用的是基础选择器h1,如果你的CSS加载在Bootstrap后仍被覆盖,可通过更具体的选择器提升权重:

  • 基于父元素的选择器:
body h1 {
  font-family: 'Montserrat', sans-serif;
  line-height: 1.5;
  font-size: 3rem;
  font-weight: 900;
}
  • 自定义类选择器(权重更高,推荐):
<h1 class="custom-heading">Montserrat black 900 font weight</h1>
.custom-heading {
  font-family: 'Montserrat', sans-serif;
  line-height: 1.5;
  font-size: 3rem;
  font-weight: 900;
}

2. 使用!important(谨慎使用)

如果不想调整选择器结构,可通过!important强制覆盖样式,这是最直接的方法,但建议仅在必要时使用,避免引发样式冲突:

h1 {
  font-family: 'Montserrat', sans-serif !important;
  line-height: 1.5 !important;
  font-size: 3rem !important;
  font-weight: 900 !important;
}

3. 自定义Bootstrap变量(推荐本地编译场景)

若你是本地编译Bootstrap 5.3的Sass文件,可通过重写变量从根源修改样式,无需额外编写覆盖CSS:

// 先引入Bootstrap变量文件
@import "../node_modules/bootstrap/scss/variables";

// 重写h1相关配置
$h1-font-weight: 900;
$h1-font-family: 'Montserrat', sans-serif;
$h1-line-height: 1.5;

// 最后引入Bootstrap主文件
@import "../node_modules/bootstrap/scss/bootstrap";

注意:此方法需要本地安装Bootstrap并使用Sass编译,无法直接适配CDN加载的Bootstrap版本。

4. 确认CSS加载顺序

确保你的自定义CSS文件在Bootstrap的CSS链接之后引入,相同权重的选择器,后加载的样式会覆盖先加载的:

<!-- 先加载Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<!-- 再加载自定义CSS -->
<link rel="stylesheet" href="your-custom-styles.css">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:42:34