bootstrap-customize

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bootstrap 5.3 Customization

Bootstrap 5.3 定制指南

Bootstrap 5.3 provides powerful customization through Sass variables, CSS custom properties, and a comprehensive theming system including built-in color modes.
Bootstrap 5.3 通过Sass变量、CSS自定义属性以及包含内置颜色模式的完整主题系统,提供了强大的定制能力。

Customization Methods

定制方法

1. CSS Variables (Runtime Customization)

1. CSS变量(运行时定制)

Bootstrap's docs call these "CSS variables" (technically CSS custom properties). Modify styles without recompiling by overriding at any level:
css
/* Global override */
:root {
  --bs-primary: #0074d9;
  --bs-primary-rgb: 0, 116, 217;
  --bs-body-font-family: 'Inter', sans-serif;
}

/* Component-level override */
.my-card {
  --bs-card-bg: #f0f0f0;
  --bs-card-border-color: transparent;
}

/* Local scope override */
.custom-button {
  --bs-btn-bg: #custom-color;
  --bs-btn-border-color: #custom-color;
  --bs-btn-hover-bg: #darker-custom;
}
Bootstrap文档中称这些为“CSS变量”(技术上是CSS自定义属性)。无需重新编译,即可在任意层级覆盖样式:
css
/* 全局覆盖 */
:root {
  --bs-primary: #0074d9;
  --bs-primary-rgb: 0, 116, 217;
  --bs-body-font-family: 'Inter', sans-serif;
}

/* 组件层级覆盖 */
.my-card {
  --bs-card-bg: #f0f0f0;
  --bs-card-border-color: transparent;
}

/* 局部作用域覆盖 */
.custom-button {
  --bs-btn-bg: #custom-color;
  --bs-btn-border-color: #custom-color;
  --bs-btn-hover-bg: #darker-custom;
}

CSS Variable Prefix

CSS变量前缀

Customize the
bs-
prefix via the
$prefix
Sass variable to avoid conflicts in projects embedding Bootstrap alongside other frameworks:
scss
$prefix: "myapp-"; // Results in --myapp-primary, --myapp-body-bg, etc.
可通过
$prefix
Sass变量自定义
bs-
前缀,避免在Bootstrap与其他框架共存的项目中发生冲突:
scss
$prefix: "myapp-"; // 生成 --myapp-primary、--myapp-body-bg 等变量

2. Sass Variables (Compile-time)

2. Sass变量(编译时定制)

For comprehensive theming, override Sass variables before importing Bootstrap:
scss
// 1. Include functions first
@import "bootstrap/scss/functions";

// 2. Override default variables
$primary: #0074d9;
$secondary: #7fdbff;
$font-family-base: 'Inter', sans-serif;
$border-radius: 0.5rem;
$enable-shadows: true;

// 3. Import Bootstrap
@import "bootstrap/scss/bootstrap";
Order matters: Variables must be set after functions but before other Bootstrap imports.
如需全面定制主题,需在导入Bootstrap前覆盖Sass变量:
scss
// 1. 先导入函数
@import "bootstrap/scss/functions";

// 2. 覆盖默认变量
$primary: #0074d9;
$secondary: #7fdbff;
$font-family-base: 'Inter', sans-serif;
$border-radius: 0.5rem;
$enable-shadows: true;

// 3. 导入Bootstrap
@import "bootstrap/scss/bootstrap";
顺序很重要:变量必须在导入函数后、其他Bootstrap导入前设置。

Color System

颜色系统

Theme Colors

主题颜色

Eight default theme colors with Sass maps and CSS properties:
scss
$theme-colors: (
  "primary":   $primary,
  "secondary": $secondary,
  "success":   $success,
  "info":      $info,
  "warning":   $warning,
  "danger":    $danger,
  "light":     $light,
  "dark":      $dark
);
八个默认主题颜色,对应Sass映射和CSS属性:
scss
$theme-colors: (
  "primary":   $primary,
  "secondary": $secondary,
  "success":   $success,
  "info":      $info,
  "warning":   $warning,
  "danger":    $danger,
  "light":     $light,
  "dark":      $dark
);

Adding Custom Colors

添加自定义颜色

scss
// Add to theme-colors map
$custom-colors: (
  "custom": #900,
  "brand": #1a73e8
);

// Merge with defaults
$theme-colors: map-merge($theme-colors, $custom-colors);
This generates all utilities:
.bg-custom
,
.text-brand
,
.btn-custom
, etc.
scss
// 添加到主题颜色映射
$custom-colors: (
  "custom": #900,
  "brand": #1a73e8
);

// 与默认颜色合并
$theme-colors: map-merge($theme-colors, $custom-colors);
这会自动生成所有相关工具类:
.bg-custom
.text-brand
.btn-custom
等。

Adding Colors with Dark Mode Support

添加支持暗色模式的颜色

Adding a color to
$theme-colors
alone won't generate proper dark mode styles for alerts, badges, and list-groups. Define variants in additional maps:
scss
// Light mode variants
$theme-colors-text: map-merge($theme-colors-text, ("custom": #712cf9));
$theme-colors-bg-subtle: map-merge($theme-colors-bg-subtle, ("custom": #e1d2fe));
$theme-colors-border-subtle: map-merge($theme-colors-border-subtle, ("custom": #bfa1fc));

// Dark mode variants
$theme-colors-text-dark: map-merge($theme-colors-text-dark, ("custom": #e1d2f2));
$theme-colors-bg-subtle-dark: map-merge($theme-colors-bg-subtle-dark, ("custom": #8951fa));
$theme-colors-border-subtle-dark: map-merge($theme-colors-border-subtle-dark, ("custom": #e1d2f2));
Without these definitions, components using
*-text-emphasis
,
*-bg-subtle
, and
*-border-subtle
patterns won't display correctly in dark mode.
仅将颜色添加到
$theme-colors
不会为警告框、徽章和列表组生成正确的暗色模式样式。需在额外映射中定义变体:
scss
// 亮色模式变体
$theme-colors-text: map-merge($theme-colors-text, ("custom": #712cf9));
$theme-colors-bg-subtle: map-merge($theme-colors-bg-subtle, ("custom": #e1d2fe));
$theme-colors-border-subtle: map-merge($theme-colors-border-subtle, ("custom": #bfa1fc));

// 暗色模式变体
$theme-colors-text-dark: map-merge($theme-colors-text-dark, ("custom": #e1d2f2));
$theme-colors-bg-subtle-dark: map-merge($theme-colors-bg-subtle-dark, ("custom": #8951fa));
$theme-colors-border-subtle-dark: map-merge($theme-colors-border-subtle-dark, ("custom": #e1d2f2));
如果没有这些定义,使用
*-text-emphasis
*-bg-subtle
*-border-subtle
模式的组件在暗色模式下将无法正确显示。

Removing Colors

删除颜色

scss
$theme-colors: map-remove($theme-colors, "info", "light");
Warning: The
primary
,
success
, and
danger
keys are required and cannot be removed. They're used by Bootstrap's core styles for links, form validation, and other components. Removing them will cause Sass compilation errors.
Safe to remove:
secondary
,
info
,
warning
,
light
,
dark
Cannot remove:
primary
,
success
,
danger
scss
$theme-colors: map-remove($theme-colors, "info", "light");
警告
primary
success
danger
键是必填项,不能删除。它们被Bootstrap核心样式用于链接、表单验证和其他组件。删除这些键会导致Sass编译错误。
可安全删除
secondary
info
warning
light
dark
不可删除
primary
success
danger

Color Modes (Dark/Light)

颜色模式(亮色/暗色)

Bootstrap 5.3 includes built-in dark mode support.
Bootstrap 5.3 内置了暗色模式支持。

Enabling Color Modes

启用颜色模式

Set
data-bs-theme
attribute on
<html>
or any element:
html
<!-- Light mode (default) -->
<html lang="en" data-bs-theme="light">

<!-- Dark mode -->
<html lang="en" data-bs-theme="dark">

<!-- Per-component -->
<div data-bs-theme="dark">
  <div class="card">Dark card in light page</div>
</div>
<html>
或任意元素上设置
data-bs-theme
属性:
html
<!-- 亮色模式(默认) -->
<html lang="en" data-bs-theme="light">

<!-- 暗色模式 -->
<html lang="en" data-bs-theme="dark">

<!-- 组件级颜色模式 -->
<div data-bs-theme="dark">
  <div class="card">亮色页面中的暗色卡片</div>
</div>

JavaScript Toggle

JavaScript切换

javascript
const toggleTheme = () => {
  const html = document.documentElement;
  const current = html.getAttribute('data-bs-theme');
  html.setAttribute('data-bs-theme', current === 'dark' ? 'light' : 'dark');
};

// With system preference
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
document.documentElement.setAttribute('data-bs-theme',
  prefersDark.matches ? 'dark' : 'light'
);

// Listen for system changes
prefersDark.addEventListener('change', (e) => {
  document.documentElement.setAttribute('data-bs-theme',
    e.matches ? 'dark' : 'light'
  );
});
javascript
const toggleTheme = () => {
  const html = document.documentElement;
  const current = html.getAttribute('data-bs-theme');
  html.setAttribute('data-bs-theme', current === 'dark' ? 'light' : 'dark');
};

// 适配系统偏好设置
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
document.documentElement.setAttribute('data-bs-theme',
  prefersDark.matches ? 'dark' : 'light'
);

// 监听系统设置变化
prefersDark.addEventListener('change', (e) => {
  document.documentElement.setAttribute('data-bs-theme',
    e.matches ? 'dark' : 'light'
  );
});

Color Mode Implementation Types

颜色模式实现类型

Bootstrap supports two approaches for color mode switching, controlled by the
$color-mode-type
Sass variable.
Bootstrap支持两种颜色模式切换方式,由
$color-mode-type
Sass变量控制。

Data Attribute Method (Default)

数据属性方法(默认)

scss
$color-mode-type: data;
Uses the
data-bs-theme
attribute on HTML elements:
html
<html data-bs-theme="dark">
Advantages:
  • Per-component theme control possible
  • User preferences can override system settings
  • Works with JavaScript theme toggles
  • Supports runtime switching without page reload
Use when: Building a theme picker UI or needing granular control over individual components.
scss
$color-mode-type: data;
使用HTML元素上的
data-bs-theme
属性:
html
<html data-bs-theme="dark">
优势
  • 支持组件级主题控制
  • 用户偏好可覆盖系统设置
  • 可与JavaScript主题切换器配合使用
  • 支持运行时切换,无需页面刷新
适用场景:构建主题选择器UI,或需要对单个组件进行精细控制时。

Media Query Method

媒体查询方法

scss
$color-mode-type: media;
Uses the
prefers-color-scheme
media query automatically:
css
@media (prefers-color-scheme: dark) {
  /* Dark mode styles applied automatically */
}
Advantages:
  • Automatic system preference detection
  • No JavaScript required
  • Simpler implementation
  • Zero runtime overhead
Disadvantages:
  • No per-component control
  • Users cannot override via UI
  • Requires page-level theming only
Use when: You want automatic system preference detection without a manual toggle.
scss
$color-mode-type: media;
自动使用
prefers-color-scheme
媒体查询:
css
@media (prefers-color-scheme: dark) {
  /* 自动应用暗色模式样式 */
}
优势
  • 自动检测系统偏好设置
  • 无需JavaScript
  • 实现更简单
  • 无运行时开销
劣势
  • 不支持组件级控制
  • 用户无法通过UI覆盖设置
  • 仅支持页面级主题设置
适用场景:希望自动适配系统偏好设置,无需手动切换时。

Custom Color Mode Colors

自定义颜色模式颜色

Override colors per mode:
scss
// Light mode colors
:root,
[data-bs-theme="light"] {
  --bs-body-bg: #ffffff;
  --bs-body-color: #212529;
}

// Dark mode colors
[data-bs-theme="dark"] {
  --bs-body-bg: #1a1a2e;
  --bs-body-color: #e1e1e1;
  --bs-primary: #6ea8fe;
}
按模式覆盖颜色:
scss
// 亮色模式颜色
:root,
[data-bs-theme="light"] {
  --bs-body-bg: #ffffff;
  --bs-body-color: #212529;
}

// 暗色模式颜色
[data-bs-theme="dark"] {
  --bs-body-bg: #1a1a2e;
  --bs-body-color: #e1e1e1;
  --bs-primary: #6ea8fe;
}

Sass Functions

Sass函数

Bootstrap provides utility functions for color manipulation and accessibility:
  • tint-color($color, $weight)
    - Lighten by mixing with white
  • shade-color($color, $weight)
    - Darken by mixing with black
  • shift-color($color, $weight)
    - Auto tint/shade based on weight sign
  • color-contrast($color)
    - Get accessible contrast color for backgrounds
scss
// Generate color scale
$primary-light: tint-color($primary, 40%);
$primary-dark: shade-color($primary, 20%);

// Auto-contrast text
.custom-badge {
  background-color: $success;
  color: color-contrast($success); // Returns #fff or #212529
}

// Hover states
.btn-custom:hover {
  background-color: shift-color($brand, 15%);
}
Additional functions:
escape-svg()
for SVG backgrounds,
add()
/
subtract()
for safe CSS calc operations.
See
references/sass-functions-mixins.md
for complete function and mixin reference.
Bootstrap提供了用于颜色处理和无障碍适配的工具函数:
  • tint-color($color, $weight)
    - 通过与白色混合提亮颜色
  • shade-color($color, $weight)
    - 通过与黑色混合加深颜色
  • shift-color($color, $weight)
    - 根据权重符号自动提亮/加深颜色
  • color-contrast($color)
    - 为背景获取符合无障碍标准的对比色
scss
// 生成颜色梯度
$primary-light: tint-color($primary, 40%);
$primary-dark: shade-color($primary, 20%);

// 自动生成对比文本色
.custom-badge {
  background-color: $success;
  color: color-contrast($success); // 返回 #fff 或 #212529
}

// 悬停状态
.btn-custom:hover {
  background-color: shift-color($brand, 15%);
}
其他函数:
escape-svg()
用于SVG背景,
add()
/
subtract()
用于安全的CSS calc运算。
完整的函数和混合宏参考请查看
references/sass-functions-mixins.md

Key Sass Variables

关键Sass变量

Typography

排版

scss
$font-family-base: system-ui, -apple-system, sans-serif;
$font-family-monospace: SFMono-Regular, Menlo, monospace;
$font-size-base: 1rem;
$font-size-sm: $font-size-base * 0.875;
$font-size-lg: $font-size-base * 1.25;
$font-weight-normal: 400;
$font-weight-bold: 700;
$line-height-base: 1.5;
$headings-font-family: null; // Inherits $font-family-base
$headings-font-weight: 500;
scss
$font-family-base: system-ui, -apple-system, sans-serif;
$font-family-monospace: SFMono-Regular, Menlo, monospace;
$font-size-base: 1rem;
$font-size-sm: $font-size-base * 0.875;
$font-size-lg: $font-size-base * 1.25;
$font-weight-normal: 400;
$font-weight-bold: 700;
$line-height-base: 1.5;
$headings-font-family: null; // 继承 $font-family-base
$headings-font-weight: 500;

Spacing

间距

scss
$spacer: 1rem;
$spacers: (
  0: 0,
  1: $spacer * 0.25,  // 0.25rem
  2: $spacer * 0.5,   // 0.5rem
  3: $spacer,         // 1rem
  4: $spacer * 1.5,   // 1.5rem
  5: $spacer * 3      // 3rem
);
scss
$spacer: 1rem;
$spacers: (
  0: 0,
  1: $spacer * 0.25,  // 0.25rem
  2: $spacer * 0.5,   // 0.5rem
  3: $spacer,         // 1rem
  4: $spacer * 1.5,   // 1.5rem
  5: $spacer * 3      // 3rem
);

Border Radius

边框圆角

scss
$border-radius: 0.375rem;
$border-radius-sm: 0.25rem;
$border-radius-lg: 0.5rem;
$border-radius-xl: 1rem;
$border-radius-xxl: 2rem;
$border-radius-pill: 50rem;
scss
$border-radius: 0.375rem;
$border-radius-sm: 0.25rem;
$border-radius-lg: 0.5rem;
$border-radius-xl: 1rem;
$border-radius-xxl: 2rem;
$border-radius-pill: 50rem;

Options Flags

选项开关

scss
$enable-caret: true;
$enable-rounded: true;
$enable-shadows: false;
$enable-gradients: false;
$enable-transitions: true;
$enable-reduced-motion: true;
$enable-smooth-scroll: true;
$enable-grid-classes: true;
$enable-container-classes: true;
$enable-negative-margins: false;
$enable-dark-mode: true;
$color-mode-type: data; // 'data' or 'media'
scss
$enable-caret: true;
$enable-rounded: true;
$enable-shadows: false;
$enable-gradients: false;
$enable-transitions: true;
$enable-reduced-motion: true;
$enable-smooth-scroll: true;
$enable-grid-classes: true;
$enable-container-classes: true;
$enable-negative-margins: false;
$enable-dark-mode: true;
$color-mode-type: data; // 'data' 或 'media'

Focus Ring

聚焦环

Bootstrap 5.3 provides variables to customize
:focus
styles across all components:
scss
$focus-ring-width: .25rem;
$focus-ring-opacity: .25;
$focus-ring-color: rgba($primary, $focus-ring-opacity);
$focus-ring-blur: 0;
$focus-ring-box-shadow: 0 0 $focus-ring-blur $focus-ring-width $focus-ring-color;
Bootstrap 5.3 提供了变量,用于定制所有组件的
:focus
样式:
scss
$focus-ring-width: .25rem;
$focus-ring-opacity: .25;
$focus-ring-color: rgba($primary, $focus-ring-opacity);
$focus-ring-blur: 0;
$focus-ring-box-shadow: 0 0 $focus-ring-blur $focus-ring-width $focus-ring-color;

Component Customization

组件定制

Button Customization

按钮定制

scss
// Global button variables
$btn-padding-y: 0.5rem;
$btn-padding-x: 1rem;
$btn-font-size: 1rem;
$btn-border-radius: $border-radius;

// Per-variant customization via CSS
.btn-primary {
  --bs-btn-bg: #0074d9;
  --bs-btn-border-color: #0074d9;
  --bs-btn-hover-bg: #0063b8;
  --bs-btn-hover-border-color: #005aa3;
  --bs-btn-active-bg: #005aa3;
  --bs-btn-active-border-color: #00518f;
}
scss
// 全局按钮变量
$btn-padding-y: 0.5rem;
$btn-padding-x: 1rem;
$btn-font-size: 1rem;
$btn-border-radius: $border-radius;

// 通过CSS定制特定变体
.btn-primary {
  --bs-btn-bg: #0074d9;
  --bs-btn-border-color: #0074d9;
  --bs-btn-hover-bg: #0063b8;
  --bs-btn-hover-border-color: #005aa3;
  --bs-btn-active-bg: #005aa3;
  --bs-btn-active-border-color: #00518f;
}

Card Customization

卡片定制

scss
$card-spacer-y: 1rem;
$card-spacer-x: 1rem;
$card-border-width: 1px;
$card-border-radius: $border-radius;
$card-border-color: rgba(0, 0, 0, 0.125);
$card-bg: $white;
$card-cap-bg: rgba(0, 0, 0, 0.03);
scss
$card-spacer-y: 1rem;
$card-spacer-x: 1rem;
$card-border-width: 1px;
$card-border-radius: $border-radius;
$card-border-color: rgba(0, 0, 0, 0.125);
$card-bg: $white;
$card-cap-bg: rgba(0, 0, 0, 0.03);

Form Customization

表单定制

scss
$input-padding-y: 0.375rem;
$input-padding-x: 0.75rem;
$input-font-size: 1rem;
$input-border-radius: $border-radius;
$input-border-color: $gray-400;
$input-focus-border-color: tint-color($primary, 50%);
$input-focus-box-shadow: 0 0 0 0.25rem rgba($primary, 0.25);
scss
$input-padding-y: 0.375rem;
$input-padding-x: 0.75rem;
$input-font-size: 1rem;
$input-border-radius: $border-radius;
$input-border-color: $gray-400;
$input-focus-border-color: tint-color($primary, 50%);
$input-focus-box-shadow: 0 0 0 0.25rem rgba($primary, 0.25);

Component Architecture

组件架构

Bootstrap uses a base-modifier pattern for component styling. Understanding this architecture helps you customize existing components and create new ones that integrate seamlessly.
Bootstrap使用基础-修饰符模式进行组件样式设计。理解该架构有助于你自定义现有组件,并创建能无缝集成的新组件。

Base and Modifier Classes

基础类与修饰符类

Components start with a base class providing core styling, then modifier classes add variants:
html
<!-- Base class provides core styling -->
<button class="btn">Base button</button>

<!-- Modifier classes add variants -->
<button class="btn btn-primary">Primary</button>
<button class="btn btn-lg">Large</button>
<button class="btn btn-primary btn-lg">Primary Large</button>
组件从提供核心样式的基础类开始,然后通过修饰符类添加变体:
html
<!-- 基础类提供核心样式 -->
<button class="btn">基础按钮</button>

<!-- 修饰符类添加变体 -->
<button class="btn btn-primary">主按钮</button>
<button class="btn btn-lg">大尺寸按钮</button>
<button class="btn btn-primary btn-lg">大尺寸主按钮</button>

Variant Generation with @each Loops

使用@each循环生成变体

Bootstrap generates color variants by iterating over
$theme-colors
:
scss
// How Bootstrap generates .alert-primary, .alert-danger, etc.
@each $state in map-keys($theme-colors) {
  .alert-#{$state} {
    --#{$prefix}alert-color: var(--#{$prefix}#{$state}-text-emphasis);
    --#{$prefix}alert-bg: var(--#{$prefix}#{$state}-bg-subtle);
    --#{$prefix}alert-border-color: var(--#{$prefix}#{$state}-border-subtle);
  }
}
Key insight: Adding a color to
$theme-colors
automatically generates variants for alerts, buttons, badges, list-groups, and more.
Bootstrap通过遍历
$theme-colors
生成颜色变体:
scss
// Bootstrap如何生成.alert-primary、.alert-danger等类
@each $state in map-keys($theme-colors) {
  .alert-#{$state} {
    --#{$prefix}alert-color: var(--#{$prefix}#{$state}-text-emphasis);
    --#{$prefix}alert-bg: var(--#{$prefix}#{$state}-bg-subtle);
    --#{$prefix}alert-border-color: var(--#{$prefix}#{$state}-border-subtle);
  }
}
关键要点:将颜色添加到
$theme-colors
会自动为警告框、按钮、徽章、列表组等生成变体。

Custom Component with Variants

带变体的自定义组件

Apply the same pattern for consistent custom components:
scss
// Base class
.callout {
  padding: var(--bs-callout-padding, 1rem);
  border-left: 4px solid var(--bs-callout-border-color, currentcolor);
  background: var(--bs-callout-bg, transparent);
}

// Generate variants from theme colors
@each $state, $value in $theme-colors {
  .callout-#{$state} {
    --bs-callout-border-color: var(--bs-#{$state});
    --bs-callout-bg: var(--bs-#{$state}-bg-subtle);
  }
}
This generates
.callout-primary
,
.callout-danger
, etc., all inheriting from the base
.callout
styles.
See
references/sass-functions-mixins.md
for
button-variant()
and other mixins that follow this pattern.
应用相同模式创建一致的自定义组件:
scss
// 基础类
.callout {
  padding: var(--bs-callout-padding, 1rem);
  border-left: 4px solid var(--bs-callout-border-color, currentcolor);
  background: var(--bs-callout-bg, transparent);
}

// 从主题颜色生成变体
@each $state, $value in $theme-colors {
  .callout-#{$state} {
    --bs-callout-border-color: var(--bs-#{$state});
    --bs-callout-bg: var(--bs-#{$state}-bg-subtle);
  }
}
这会生成
.callout-primary
.callout-danger
等类,均继承自基础
.callout
样式。
遵循此模式的
button-variant()
等混合宏参考请查看
references/sass-functions-mixins.md

Creating Custom Components

创建自定义组件

Use Bootstrap's mixins and functions for consistent components:
scss
.custom-component {
  // Use Bootstrap's spacing
  padding: map-get($spacers, 3);
  margin-bottom: map-get($spacers, 4);

  // Use Bootstrap's colors
  background-color: var(--bs-body-bg);
  color: var(--bs-body-color);
  border: 1px solid var(--bs-border-color);
  border-radius: var(--bs-border-radius);

  // Use Bootstrap's shadows
  @if $enable-shadows {
    box-shadow: $box-shadow-sm;
  }

  // Responsive behavior
  @include media-breakpoint-up(md) {
    padding: map-get($spacers, 4);
  }
}
使用Bootstrap的混合宏和函数创建风格一致的组件:
scss
.custom-component {
  // 使用Bootstrap的间距设置
  padding: map-get($spacers, 3);
  margin-bottom: map-get($spacers, 4);

  // 使用Bootstrap的颜色
  background-color: var(--bs-body-bg);
  color: var(--bs-body-color);
  border: 1px solid var(--bs-border-color);
  border-radius: var(--bs-border-radius);

  // 使用Bootstrap的阴影
  @if $enable-shadows {
    box-shadow: $box-shadow-sm;
  }

  // 响应式行为
  @include media-breakpoint-up(md) {
    padding: map-get($spacers, 4);
  }
}

Optimization

优化

Bootstrap's full bundle is substantial. Use these strategies to reduce production bundle size.
Bootstrap的完整包体积较大。可通过以下策略减小生产环境包体积。

Lean Sass Imports

精简Sass导入

Import only the components you use:
scss
// Required core
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";

// Optional - import only what you use
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/containers";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/buttons";
See
examples/selective-imports.scss
for a complete minimal build example.
仅导入你需要的组件:
scss
// 必需的核心文件
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";

// 可选 - 仅导入需要的部分
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/containers";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/buttons";
完整的最小构建示例请查看
examples/selective-imports.scss

Lean JavaScript Imports

精简JavaScript导入

Tree-shake Bootstrap JavaScript by importing individual plugins:
javascript
// Instead of importing everything
// import * as bootstrap from 'bootstrap';

// Import only what you need
import Modal from 'bootstrap/js/dist/modal';
import Dropdown from 'bootstrap/js/dist/dropdown';
import Collapse from 'bootstrap/js/dist/collapse';

// Initialize manually
const modal = new Modal('#myModal');
Note: Some plugins have dependencies (e.g., Dropdown requires Popper.js). Check plugin documentation.
通过导入单个插件实现Bootstrap JavaScript的树摇优化:
javascript
// 不要导入全部内容
// import * as bootstrap from 'bootstrap';

// 仅导入需要的插件
import Modal from 'bootstrap/js/dist/modal';
import Dropdown from 'bootstrap/js/dist/dropdown';
import Collapse from 'bootstrap/js/dist/collapse';

// 手动初始化
const modal = new Modal('#myModal');
注意:部分插件存在依赖(例如Dropdown需要Popper.js)。请查看插件文档。

Remove Unused CSS with PurgeCSS

使用PurgeCSS移除未使用的CSS

PurgeCSS removes unused styles from your production build:
javascript
// postcss.config.js
module.exports = {
  plugins: [
    require('@fullhuman/postcss-purgecss')({
      content: ['./src/**/*.html', './src/**/*.js'],
      // Safelist Bootstrap's dynamic classes
      safelist: {
        standard: [/^modal/, /^show/, /^fade/, /^collapse/, /^offcanvas/],
        deep: [/^tooltip/, /^popover/, /^bs-/]
      }
    })
  ]
}
Bootstrap dynamically adds classes like
show
,
fade
,
collapsing
. Always safelist these patterns.
PurgeCSS可从生产构建中移除未使用的样式:
javascript
// postcss.config.js
module.exports = {
  plugins: [
    require('@fullhuman/postcss-purgecss')({
      content: ['./src/**/*.html', './src/**/*.js'],
      // 保留Bootstrap的动态类
      safelist: {
        standard: [/^modal/, /^show/, /^fade/, /^collapse/, /^offcanvas/],
        deep: [/^tooltip/, /^popover/, /^bs-/]
      }
    })
  ]
}
Bootstrap会动态添加
show
fade
collapsing
等类。请务必保留这些模式的类。

Autoprefixer Configuration

Autoprefixer配置

Configure browser support to avoid unnecessary vendor prefixes:
text
undefined
配置浏览器支持范围,避免不必要的浏览器前缀:
text
undefined

.browserslistrc

.browserslistrc

= 0.5% last 2 major versions not dead not Explorer <= 11

This is Bootstrap's default configuration. Adjust based on your audience.
= 0.5% last 2 major versions not dead not Explorer <= 11

这是Bootstrap的默认配置。可根据你的目标受众进行调整。

Production Best Practices

生产环境最佳实践

Minification: Use minified distribution files in production:
  • bootstrap.min.css
    (not
    bootstrap.css
    )
  • bootstrap.bundle.min.js
    (not
    bootstrap.bundle.js
    )
Compression: Enable gzip or Brotli on your server:
nginx
undefined
压缩:在生产环境中使用压缩后的分发文件:
  • bootstrap.min.css
    (而非
    bootstrap.css
  • bootstrap.bundle.min.js
    (而非
    bootstrap.bundle.js
压缩传输:在服务器上启用gzip或Brotli压缩:
nginx
undefined

nginx.conf

nginx.conf

gzip on; gzip_types text/css application/javascript;

**Non-blocking Loading**: Use `defer` for non-critical scripts:

```html
<!-- Critical CSS in head -->
<link rel="stylesheet" href="bootstrap.min.css">

<!-- Scripts at end of body with defer -->
<script src="bootstrap.bundle.min.js" defer></script>
HTTPS: Always serve Bootstrap over HTTPS. CDN links require secure connections and modern browsers may block mixed content.
gzip on; gzip_types text/css application/javascript;

**非阻塞加载**:对非关键脚本使用`defer`属性:

```html
<!-- 关键CSS放在head中 -->
<link rel="stylesheet" href="bootstrap.min.css">

<!-- 脚本放在body末尾并使用defer -->
<script src="bootstrap.bundle.min.js" defer></script>
HTTPS:始终通过HTTPS提供Bootstrap资源。CDN链接需要安全连接,现代浏览器可能会阻止混合内容。

Security Considerations

安全注意事项

Content Security Policy (CSP)

内容安全策略(CSP)

Bootstrap uses embedded SVGs in CSS (
data:
URIs) for consistent cross-browser styling. If your application has a strict Content Security Policy, some components may not display correctly.
Affected components:
  • Accordion (collapse/expand icons)
  • Carousel (prev/next controls)
  • Close button (X icon)
  • Form controls (checkboxes, radios, switches, validation icons)
  • Navbar toggle (hamburger icon)
  • Select menus (dropdown arrow)
Symptoms of CSP conflicts:
  • Form checkboxes don't show checkmarks
  • Accordions missing expand/collapse icons
  • Navbar hamburger menus appear broken
  • Select dropdowns lack arrows
Solutions:
  1. Replace with local assets - Use the
    escape-svg()
    function with locally hosted SVG files:
scss
// Custom checkbox with local SVG instead of data: URI
$form-check-input-checked-bg-image: url("/assets/icons/check.svg");
  1. Adjust CSP - If appropriate for your security requirements, allow the inline SVG data URIs in your policy
  2. Use Bootstrap Icons font - Replace SVG icons with the Bootstrap Icons font variant
For strict CSP environments, audit Bootstrap's SVG usage during customization planning.
Bootstrap在CSS中使用嵌入式SVG(
data:
URI)以实现跨浏览器一致的样式。如果你的应用有严格的内容安全策略,部分组件可能无法正确显示。
受影响的组件
  • 手风琴(展开/折叠图标)
  • 轮播(上一个/下一个控件)
  • 关闭按钮(X图标)
  • 表单控件(复选框、单选框、开关、验证图标)
  • 导航栏切换按钮(汉堡图标)
  • 选择菜单(下拉箭头)
CSP冲突症状
  • 表单复选框不显示勾选标记
  • 手风琴缺少展开/折叠图标
  • 导航栏汉堡菜单显示异常
  • 选择下拉菜单缺少箭头
解决方案
  1. 替换为本地资源 - 使用
    escape-svg()
    函数配合本地托管的SVG文件:
scss
// 使用本地SVG替换data: URI的自定义复选框
$form-check-input-checked-bg-image: url("/assets/icons/check.svg");
  1. 调整CSP - 如果符合你的安全要求,在策略中允许内联SVG data URI
  2. 使用Bootstrap Icons字体 - 将SVG图标替换为Bootstrap Icons字体变体
对于严格的CSP环境,在定制规划阶段需审核Bootstrap的SVG使用情况。

Additional Resources

额外资源

Reference Files

参考文件

  • references/sass-variables.md
    - Complete Sass variable reference
  • references/sass-functions-mixins.md
    - Complete function and mixin reference
  • references/sass-variables.md
    - 完整的Sass变量参考
  • references/sass-functions-mixins.md
    - 完整的函数和混合宏参考

Example Files

示例文件

  • examples/color-mode-toggle.html
    - Complete dark/light mode toggle with system preference detection
  • examples/custom-theme-demo.html
    - Runtime CSS variable theming without Sass compilation
  • examples/color-mode-toggle.html
    - 包含系统偏好检测的完整亮色/暗色模式切换示例
  • examples/custom-theme-demo.html
    - 无需Sass编译的运行时CSS变量主题定制示例