版本要求:色彩模式是 Bootstrap 5.3.0 中引入的新特性。确保你的 Bootstrap 版本 ≥ 5.3.0。
工作原理
Bootstrap 5.3 的色彩模式基于 CSS 自定义属性(CSS 变量)和 data-bs-theme 属性实现。核心思路是:
- 所有颜色和背景通过
--bs-* CSS 变量定义
- 在
<html> 或 <body> 上设置 data-bs-theme="dark" 触发深色模式
- Bootstrap 的 CSS 变量会自动响应主题变化,无需额外编写样式
快速上手
在页面根元素上设置 data-bs-theme 属性:
<html lang="zh-CN" data-bs-theme="dark">
...
</html>
切换后,页面中的所有 Bootstrap 组件会自动适配深色背景和配色方案。
主题切换示例
<script>
function switchTheme(theme) {
if (theme === 'auto') {
document.documentElement.removeAttribute('data-bs-theme');
} else {
document.documentElement.setAttribute('data-bs-theme', theme);
}
}
</script>
API 参考
Bootstrap 提供了完整的 JavaScript API 用于检测和切换色彩模式:
// 检测当前主题
const theme = document.documentElement.getAttribute('data-bs-theme');
// 返回 'light'、'dark' 或 null(自动模式)
// 检测系统主题偏好
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (e.matches) {
document.documentElement.setAttribute('data-bs-theme', 'dark');
} else {
document.documentElement.setAttribute('data-bs-theme', 'light');
}
});
Sass 变量覆盖
如果你使用 Sass 源码编译,可以通过变量自定义深色模式的配色:
// 自定义深色模式颜色
$body-bg-dark: #1a1a2e;
$body-color-dark: #e0e0e0;
$primary-dark: #bb86fc;
$secondary-dark: #03dac6;
// 导入 Bootstrap
@import "bootstrap/scss/bootstrap";
组件适配
Bootstrap 5.3 中的所有组件都已适配色彩模式,以下是一些示例:
导航栏
<nav class="navbar navbar-expand-lg">
<div class="container">
<a class="navbar-brand" href="#">品牌</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</nav>
卡片
<div class="card">
<div class="card-body">
<h5 class="card-title">卡片标题</h5>
<p class="card-text">卡片在深色模式下会自动适配背景和文字颜色。</p>
</div>
</div>
表格
<table class="table">
<thead>
<tr><th>名称</th><th>价格</th></tr>
</thead>
<tbody>
<tr><td>产品 A</td><td>¥99</td></tr>
</tbody>
</table>
自定义主题变量
Bootstrap 5.3 为深色模式定义了独立的 CSS 变量集,可通过以下方式自定义:
[data-bs-theme="dark"] {
--bs-body-bg: #121212;
--bs-body-color: #e0e0e0;
--bs-primary: #bb86fc;
--bs-primary-rgb: 187, 134, 252;
--bs-secondary: #03dac6;
--bs-secondary-rgb: 3, 218, 198;
--bs-border-color: #333;
--bs-link-color: #bb86fc;
--bs-link-hover-color: #ce93d8;
}
与第三方库配合
色彩模式机制完全基于 CSS 变量,因此可以与任何支持 CSS 变量的第三方库无缝配合:
- Bootstrap Icons:图标颜色会自动继承文字颜色
- Prism.js / Highlight.js:代码高亮需额外配置深色主题
- Chart.js / ECharts:图表颜色需通过配置动态切换
注意:bootstrap.bundle.js 版本 5.3.0+ 已经内置色彩模式支持。如果你的项目使用旧版本,升级到 5.3.x 即可。
相关文档