Bootstrap 5 的自定义颜色需通过 Sass 的 $theme-colors 扩展并调用 @include theme-colors() 才能生成对应实用类;仅声明 CSS 变量 --bs-custom-blue 不会触发类名生成,且必须用 map-merge 增量添加、手动补全 RGB 等衍生变量及按钮 outline 相关变量。

Bootstrap 5 的颜色实用类(如 .text-primary、.bg-success)不会自动响应你新增的 CSS 变量(比如 --bs-custom-blue),必须通过 Sass 编译时扩展 $theme-colors 并显式调用 @include theme-colors() 才能生成对应类名。
为什么加了 --bs-custom-blue 却没有 .text-custom-blue
CSS 自定义变量和实用类是两套独立机制:--bs-custom-blue 只影响直接使用 color: var(--bs-custom-blue) 的组件(如部分 5.3+ 按钮背景),但不会触发 Bootstrap 的类名生成逻辑。实用类全部由 Sass 的 $theme-colors map + theme-colors() mixin 编译产出。
- 只在
:root中声明--bs-custom-blue→ JS 可读取,但 HTML 类无效 - 只在 Sass 中定义
"custom-blue": #0f766e但没调用@include theme-colors()→ 编译后无任何.text-custom-blue类 - 正确做法:Sass 中定义 map + 调用 mixin + (可选)手动补 CSS 变量供 JS 或动态样式使用
$theme-colors 扩展必须用 map-merge(),不能直接赋值
直接写 $theme-colors: ("custom-blue": #0f766e); 会覆盖掉 Bootstrap 默认的 primary、success 等所有内置色,导致 .btn-primary 失效。
- ✅ 正确:用
map-merge($theme-colors, ("custom-blue": #0f766e))增量添加 - ⚠️ 键名必须加引号:
"custom-blue",不加会报 Sass 编译错误 - ⚠️ 衍生变量(如
$custom-blue-rgb)需手动定义,否则text-custom-blue在深色背景下可能对比度不足
按钮类(.btn-outline-*)边框/文字色不随新主题变?查这三个变量
.btn-outline-custom-blue 的边框、文字、背景透明度不是直接读 --bs-custom-blue,而是依赖三组独立变量:
-
--bs-btn-outline-border-color:控制边框色(默认 fallback 是--bs-border-color) -
--bs-btn-outline-color:控制文字色(默认 fallback 是--bs-emphasis-color) -
--bs-btn-outline-bg:控制背景透明度(默认是transparent) - 它们不会自动从
--bs-custom-blue推导——必须手动为每个新主题色设置这组变量,或用媒体查询 +data-bs-theme属性做条件覆盖
运行时切换主题时,--bs-primary-rgb 等衍生变量必须同步更新
Bootstrap 组件大量使用 rgba(var(--bs-primary-rgb), .1) 这类语法,如果只改 --bs-primary 却漏掉 --bs-primary-rgb,悬停背景、表单 focus ring、卡片分隔线都会失色或变黑。
- 推荐把每个主题配置写成完整对象,包含所有衍生变量:
"--bs-primary-rgb": "37, 99, 235"、"--bs-primary-text-emphasis": "#1e3a8a"、"--bs-primary-border-subtle": "#dbeafe" - 不要靠 JS 解析十六进制转 RGB——浏览器不支持运行时计算,必须提前算好字符串
- localStorage 存的是主题名,不是变量值;切换时应从预置对象里整块取值注入
<style id="theme-styles">,避免拼接遗漏
最易被忽略的是:新增主题色后,.btn-outline-* 和 .form-control:focus 的表现完全取决于你是否手动补全了那套“RGB + 文字强调 + 边框浅色”变量组合,而不是仅仅加了一个 --bs-custom-blue。


















