bootstrap 5 需通过 sass 变量扩展 $theme-colors,必须用 map-merge() 增量添加并同步定义 -rgb 变量,且 @include theme-colors() 需在全部 @import 后调用才能生成对应工具类。

Bootstrap 5 没有 $theme-colors 配置文件,它不读 JSON/YAML/JS 配置;所有颜色定制必须通过 Sass 编译前重写变量实现。
为什么改了 $theme-colors 却没生成 .btn-custom-* 类?
Bootstrap 不会自动为新增的 $theme-colors 键名生成工具类——它只对内置 key(如 primary、success)默认输出。新增颜色需显式调用 @include theme-colors() 才能触发类生成。
- 确保在自定义 SCSS 文件末尾已导入
bootstrap/scss/utilities(不是仅utilities/api),否则theme-colorsmixin 不可用 -
@include theme-colors()必须放在所有@import之后、编译前执行,顺序错则无效 - 键名必须是字符串:
"custom-red"✅,custom-red❌(Sass 报错) - 如果只导入了部分 Bootstrap 模块(比如跳过
utilities),新颜色类将完全不会出现在最终 CSS 中
如何安全扩展 $theme-colors 而不覆盖默认色?
直接赋值 $theme-colors: ("primary": #0d6efd, "custom": #ff6b35); 会丢掉 secondary、info 等所有默认色,导致 .btn-secondary 失效。正确做法是用 map-merge() 增量添加。
- 先
@import "bootstrap/scss/functions";(必需,map-merge在此定义) - 再写:
$theme-colors: map-merge($theme-colors, ("amber": #ffc107, "teal": #20c997)); - 这样保留全部原生 color key,同时支持
bg-amber、text-teal等新类 - 注意:
$theme-colors必须在@import "bootstrap/scss/variables"之前重定义,否则被忽略
为什么 .btn-outline-custom 边框还是灰色?
$theme-colors 只控制主体色,但 .btn-outline-* 的边框和文字色由硬编码对比度逻辑决定:Bootstrap 内部用 $theme-color-contrast-dark 和 $theme-color-contrast-light 判断该用黑还是白,**并不根据你的新颜色自动计算**。
- 新增颜色如
"indigo": #4b0082默认仍走灰色边框,因为没配套设置--bs-indigo-rgb或$indigo-rgb - 若要让 outline 类正常工作,必须手动补全 RGB 变量:
$indigo-rgb: 75, 0, 130;,并确保它在functions后、variables前声明 - 更稳妥的做法是:所有新颜色都用十六进制或
rgb()显式定义,并同步提供-rgb版本,否则rgba(var(--bs-indigo-rgb), .1)会失效
真正容易被忽略的是衍生变量链:改一个 $primary,得连带更新 $primary-rgb、$primary-text-emphasis、$primary-bg-subtle —— 少一个,就可能在 alert 文字、卡片背景或 disabled 按钮上看到不可读的灰蒙蒙效果。











