Sass

利用我们的 Sass 源文件,使用变量、映射、混入和函数来帮助你更快地构建并自定义你的项目。

关于 Sass

Sass 是一个 CSS 预处理器,为标准 CSS 添加了变量、嵌套、混入和函数等特性。你编写 .scss 文件并编译它们,输出是浏览器能够理解的纯 CSS。如果你刚接触 Sass,请查看 Sass 文档学习基础知识。

Bootstrap 使用 Sass 编写。我们的源 .scss 文件使用 Sass 映射定义设计 tokens,使用混入生成重复的 CSS 模式,并使用 @use/@forward 模块系统组织一切。编译时,这些 Sass 文件生成驱动每个 Bootstrap 组件和工具类的 CSS。这让你能够覆盖 token 值、移除未使用的组件,或用自己的内容扩展系统。如果你不需要那种级别的控制,可以完全跳过 Sass,改为在运行时通过 CSS 自定义属性进行自定义。

刚接触 Sass 和 Bootstrap? 从我们的 npm 指南开始进行分步设置,或查看我们的示例仓库获取即用型入门项目。

文件结构

只要有可能,请避免修改 Bootstrap 的核心文件。对于 Sass,这意味着创建你自己的样式表来导入 Bootstrap,以便你可以修改和扩展它。假设你使用 npm 或 yarn 之类的包管理器,你将拥有如下文件结构:

TEXT
          your-project/
├── scss/
│   └── custom.scss
└── node_modules/
│   └── bootstrap/
│       ├── js/
│       └── scss/
└── index.html
        

如果你已下载我们的源文件而不使用包管理器,则需要手动创建类似该结构的内容,将 Bootstrap 的源文件与自己的文件分开。

TEXT
          your-project/
├── scss/
│   └── custom.scss
├── bootstrap/
│   ├── js/
│   └── scss/
└── index.html
        

导入

在你的 custom.scss 中,你将导入 Bootstrap 的 Sass 源文件。你有两个选择:包含所有 Bootstrap,或选择你需要的部分。我们鼓励后者,但请注意我们的组件之间有一些要求和依赖关系。你还需要为我们的插件包含一些 JavaScript。

SCSS
          // Custom.scss
// Option A: Include all of Bootstrap

@use "../node_modules/bootstrap/scss/bootstrap";

// Then add additional custom code here
        
SCSS
          // Custom.scss
// Option B: Include parts of Bootstrap

// 1. Include root first (configuration, colors, tokens, and CSS layers)
@use "../node_modules/bootstrap/scss/root";

// 2. Include any other partials as needed
@use "../node_modules/bootstrap/scss/content";
@use "../node_modules/bootstrap/scss/layout";
@use "../node_modules/bootstrap/scss/forms";
@use "../node_modules/bootstrap/scss/buttons";

// 3. Components
@use "../node_modules/bootstrap/scss/alert";
@use "../node_modules/bootstrap/scss/card";
// ...

// 4. Helpers and utilities
@use "../node_modules/bootstrap/scss/helpers";
@use "../node_modules/bootstrap/scss/utilities/api";

// 5. Add additional custom code here
        

设置到位后,你就可以开始修改 custom.scss 中的任何 Sass token 映射。我们建议使用 bootstrap.scss 文件中的完整导入栈作为起点。

@forward "banner";

// Configuration variables and maps, such as $utilities. Forwarding config makes
// them configurable from this entrypoint with `@use ... with (...)`. Emits no CSS.
@forward "config";

@forward "colors";

// Theme color maps ($theme-colors, $theme-bgs, etc.). Forwarding makes them
// configurable from this entrypoint with `@use ... with (...)`. Emits no CSS.
@forward "theme";

// Global CSS variables, layer definitions, and configuration
@forward "root";

// Subdir imports
@forward "content";
@forward "layout";
@forward "forms";
@forward "buttons";

// Components
@forward "accordion";
@forward "alert";
@forward "avatar";
@forward "badge";
@forward "breadcrumb";
@forward "chip";
@forward "card";
@forward "carousel";
@forward "dialog";
@forward "menu";
@forward "list-group";
@forward "nav";
@forward "nav-overflow";
@forward "navbar";
@forward "drawer";
@forward "pagination";
@forward "placeholder";
@forward "popover";
@forward "progress";
@forward "spinner";
@forward "stepper";
@forward "toasts";
@forward "tooltip";
@forward "transitions";

// Helpers
@forward "helpers";

// Utilities
@forward "utilities/api";

变量、函数和混入

@use 将模块的成员置于命名空间之后。默认情况下,命名空间是 URL 的最后一部分。使用选项 A 时,Bootstrap 的变量、函数和混入位于 bootstrap 之后:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap";

.custom-element {
  padding: bootstrap.$spacer * .5;
}

@include bootstrap.media-breakpoint-up(md) {
  .custom-element {
    padding: bootstrap.$spacer;
  }
}
        

要不带前缀地使用名称(如同 v5 中的 @import),请使用 as * 加载 Bootstrap。你仍然可以通过 with () 传递覆盖值:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" as * with (
  $spacer: 1.25rem
);

.custom-element {
  padding: $spacer;
}
        

使用选项 B 时,请使用定义该成员的 partial 的命名空间。例如,@use "../node_modules/bootstrap/scss/config" 后 $spacer 为 config.$spacer,而 @use "../node_modules/bootstrap/scss/layout" 后断点混入为 layout.media-breakpoint-up()。

@use 规则仅适用于包含它的文件。请将其添加到每个使用 Bootstrap 成员的你自己的 partial 中。

编译

为了在浏览器中将自定义 Sass 代码用作 CSS,你需要一个 Sass 编译器。Sass 以 CLI 包形式提供,但你也可以使用 Gulp 或 Webpack 等其他构建工具或 GUI 应用程序编译它。某些 IDE 也内置了 Sass 编译器或提供可下载的扩展。

我们喜欢使用 CLI 编译 Sass,但你可以使用任何你偏好的方法。从命令行运行以下命令:

Shell
          # Install Sass globally
npm install -g sass

# Watch your custom Sass for changes and compile it to CSS
sass --watch ./scss/custom.scss ./css/custom.css
        

在 sass-lang.com/install 和使用 VS Code 编译了解更多关于你的选项。

将 Bootstrap 与另一个构建工具一起使用? 考虑阅读我们关于使用 Webpack、Parcel 或 Vite 编译的指南。我们的 GitHub 示例仓库中还有可用于生产的演示。

包含

CSS 编译完成后,你可以将其包含到 HTML 文件中。在 index.html 中,你需要包含编译后的 CSS 文件。如果你更改了编译后 CSS 文件的路径,请务必更新。

HTML
          <!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Custom Bootstrap</title>
    <link href="/css/custom.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>
        

Token 架构

Bootstrap v6 使用基于 CSS 自定义属性的分层 token 系统。Sass 映射在编译时定义 tokens,而 CSS 自定义属性由这些映射生成以供运行时使用。

各层从最低到最高级别:

  1. 颜色比例(_colors.scss)——在 oklch() 中定义的基础色相变量使用 color-mix() 生成完整的色阶(025–975)作为 CSS 自定义属性。例如 --blue-500、--red-200、--gray-900。

  2. 主题颜色(_theme.scss)——$theme-colors 映射定义诸如 primary、success 和 danger 等语义颜色角色。每个主题颜色都是一个带有子键的嵌套映射:base、text、text-emphasis、bg、bg-subtle、bg-muted、border、focus-ring 和 contrast。

  3. 全局 tokens(_theme.scss 和 _root.scss)——用于背景($theme-bgs)、前景($theme-fgs)和边框($theme-borders)的语义 tokens 与 $root-tokens 映射一起定义,后者将所有内容聚合为 :root CSS 自定义属性。

  4. 组件 tokens(例如 _alert.scss)——每个组件定义自己的 $*-tokens 映射(例如 $alert-tokens),该映射作为限定到组件类的 CSS 自定义属性输出。

Token 默认值

Bootstrap 中的每个 token 映射都包含 !default 标志,允许你在加载 Bootstrap 文件之前覆盖值。由于 Bootstrap 使用 Sass 模块(@use/@forward),你可以使用 with () 语法覆盖 !default 变量。对于 CSS 自定义属性 tokens,你有两条自定义路径:

  1. 在编译时——覆盖生成 CSS 自定义属性的 Sass 映射。
  2. 在运行时——直接在样式表中覆盖 CSS 自定义属性,无需 Sass。

编译时覆盖

要在编译时覆盖 token 值,请在导入 Bootstrap 时使用 @use ... with ()。你只需包含想要更改的键——Bootstrap 使用 defaults() 函数将你的覆盖与默认值合并,因此所有其他 tokens 保持不变。

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" with (
  $root-tokens: (
    --border-radius: .25rem,
    --spacer: 1.5rem,
  ),
  $alert-tokens: (
    --alert-padding-x: 2rem,
    --alert-border-radius: 1rem,
  )
);
        

在底层,每个 token 映射都使用两步模式:

SCSS
          $alert-tokens: () !default;
$alert-tokens: defaults(
  (
    // Default tokens here
  ),
  $alert-tokens
);
        

() !default 声明接收你的 with() 覆盖。然后 defaults() 将你的条目合并到内置默认值之上,因此未指定的键保留其原始值。任何设置为 null 的键都会从映射中完全移除,让你可以丢弃不需要的 tokens。

运行时覆盖

由于 tokens 作为 CSS 自定义属性输出,你可以直接在 CSS 中覆盖它们,无需任何 Sass 编译:

CSS
          :root {
  --border-radius: .25rem;
  --primary-base: oklch(55% 0.25 260);
  --bg-body: #f8f9fa;
}
        

你还可以将覆盖限定到特定组件:

CSS
          .alert {
  --alert-padding-x: 2rem;
  --alert-padding-y: 1.5rem;
  --alert-border-radius: 1rem;
}
        

使用 Bootstrap npm 入门项目吧! 前往 Sass & JS 示例 模板仓库,了解如何在您自己的 npm 项目中构建并自定义 Bootstrap。其中包含 Sass 编译器、Autoprefixer、Stylelint、PurgeCSS 和 Bootstrap Icons。

映射和循环

Bootstrap 包含若干 Sass 映射,用于生成相关的 CSS 自定义属性系列。这些映射都包含 !default 标志,可以被覆盖。

主题颜色映射

$theme-colors 映射定义语义调色板。每个条目都是一个嵌套映射,带有 base、text、bg、border 等子键。有关完整映射、子键参考和使用示例,请参阅主题文档。

要在编译时添加、修改或移除主题颜色,请通过主入口点使用 @use ... with () 配置 $theme-colors。defaults() 将你的映射合并到内置映射之上,因此标准主题保持不变,你只需添加所需内容:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" with (
  $theme-colors: (
    "brand": (
      "base": var(--indigo-500),
      "fg": light-dark(var(--indigo-600), var(--indigo-400)),
      "fg-emphasis": light-dark(var(--indigo-800), var(--indigo-300)),
      "bg": var(--indigo-500),
      "bg-subtle": light-dark(var(--indigo-100), var(--indigo-900)),
      "bg-muted": light-dark(var(--indigo-200), var(--indigo-800)),
      "border": light-dark(var(--indigo-300), var(--indigo-600)),
      "focus-ring": light-dark(color-mix(in oklch, var(--indigo-500) 50%, var(--bg-body)), color-mix(in oklch, var(--indigo-500) 75%, var(--bg-body))),
      "contrast": var(--white)
    )
  )
);
        

每个主题颜色都是一个嵌套映射,因此合并只深入一层。要更改内置主题的某个子键,请为该主题传入整个子映射。部分子映射会替换该主题的其他子键,而不是与它们合并。要移除主题,将其键设置为 null。

全局 token 映射

背景($theme-bgs)、前景($theme-fgs)和边框($theme-borders)token 映射定义语义层颜色。这些也在主题文档中有所涵盖。

根 tokens($root-tokens)

$root-tokens 映射聚合诸如字体、间距、边框和表单变量等全局设计 tokens。主题颜色、背景、前景和边框 tokens 在输出前被合并到其中。

// stylelint-disable @stylistic/value-list-max-empty-lines, @stylistic/function-max-empty-lines, custom-property-no-missing-var-function
// stylelint-disable-next-line scss/dollar-variable-default
$root-tokens: defaults(
  (
    --black: #{$black},
    --white: #{$white},

    --gradient: #{$gradient},

    // scss-docs-start root-body-variables
    // The stack omits system-ui. It resolves to the user interface font of the
    // locale, which shows non-Latin text incorrectly. See twbs/bootstrap#42703.
    --body-font-family: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', 'Liberation Sans', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'",
    --body-font-size: 1rem,
    --body-font-weight: var(--font-weight-normal),
    --body-line-height: 1.5,
    // scss-docs-end root-body-variables

    --heading-color: inherit,

    --hr-border-color: var(--border-color),

    --link-color: light-dark(var(--primary-base), var(--primary-fg)),
    --link-decoration: underline,
    --link-underline-offset: .2em,
    --link-hover-color: color-mix(in oklch, var(--link-color) 90%, #000),

    --font-mono: "ui-monospace, 'SF Mono', SFMono-Regular, Menlo, Monaco, 'Cascadia Mono', Consolas, 'Liberation Mono', monospace",
    --code-font-size: .875em,
    --code-color: var(--fg-2),

    // scss-docs-start root-border-var
    --border-width: #{$border-width},
    --border-width-keyline: .5px,
    --border-style: #{$border-style},
    --border-color: light-dark(var(--gray-200), var(--gray-700)),
    --border-color-translucent: color-mix(in oklch, var(--fg-body) 15%, transparent),
    // scss-docs-end root-border-var

    // scss-docs-start root-box-shadow-variables
    // --box-shadow* tokens are generated below (see root-box-shadow-loop) from
    // the shared $shadows map in scss/_config.scss, which reads these two.
    --shadow-color: #000,
    --shadow-strength: 1,
    // scss-docs-end root-box-shadow-variables

    // scss-docs-start root-transition-variables
    // Shared easing curve for overlay components (dialog, drawer, menu)
    --transition-timing-overlay: cubic-bezier(.22, 1, .36, 1),
    // scss-docs-end root-transition-variables

    --spacer: #{$spacer},

    // scss-docs-start root-focus-variables
    --focus-ring-width: 3px,
    --focus-ring-offset: 1px,
    --focus-ring-color: var(--primary-focus-ring),
    --focus-ring: var(--focus-ring-width) solid var(--focus-ring-color),
    // scss-docs-end root-focus-variables

    // scss-docs-start root-form-variables
    --control-checked-bg: var(--primary-base),
    --control-checked-border-color: var(--control-checked-bg),
    --control-active-bg: var(--primary-base),
    --control-active-border-color: var(--control-active-bg),
    --control-disabled-bg: var(--bg-3),
    --control-disabled-opacity: .65,
    // Shared motion for checkbox/radio marks; slight overshoot so the mark pops in
    --control-transition-duration: .15s,
    --control-transition-timing: cubic-bezier(.34, 1.56, .64, 1),

    --btn-input-fg: var(--fg-body),
    --btn-input-bg: var(--bg-body),

    --btn-input-gap: .375rem,
    --btn-input-min-height: 2.375rem,
    --btn-input-padding-y: .375rem,
    --btn-input-padding-x: .75rem,
    --btn-input-font-size: var(--body-font-size),
    --btn-input-font-weight: var(--font-weight-normal),
    --btn-input-line-height: var(--body-line-height),
    --btn-input-border-radius: var(--radius-5),

    --btn-input-xs-gap: var(--spacer-1),
    --btn-input-xs-min-height: 1.5rem,
    --btn-input-xs-padding-y: .125rem,
    --btn-input-xs-padding-x: .5rem,
    --btn-input-xs-font-size: var(--font-size-xs),
    --btn-input-xs-line-height: 1.125,
    --btn-input-xs-border-radius: var(--radius-5),

    --btn-input-sm-gap: .375rem,
    --btn-input-sm-min-height: 2rem,
    --btn-input-sm-padding-y: .25rem,
    --btn-input-sm-padding-x: .625rem,
    --btn-input-sm-font-size: var(--font-size-sm),
    --btn-input-sm-line-height: var(--line-height-sm),
    --btn-input-sm-border-radius: var(--radius-5),

    --btn-input-lg-gap: .375rem,
    --btn-input-lg-min-height: 2.75rem,
    --btn-input-lg-padding-y: .5rem,
    --btn-input-lg-padding-x: 1rem,
    --btn-input-lg-font-size: var(--font-size-md),
    --btn-input-lg-line-height: var(--line-height-md),
    --btn-input-lg-border-radius: var(--radius-7),
    // scss-docs-end root-form-variables
  ),
  $root-tokens
);
// stylelint-enable @stylistic/value-list-max-empty-lines, @stylistic/function-max-empty-lines, custom-property-no-missing-var-function

所有根 tokens 都作为 CSS 自定义属性输出到 :root:

// Generate semantic theme colors
@each $color-name, $color-map in $theme-colors {
  @each $key, $value in $color-map {
    $root-tokens: map.set($root-tokens, --#{$color-name}-#{$key}, $value);
  }
}

// Generate background tokens
@each $key, $value in $theme-bgs {
  $root-tokens: map.set($root-tokens, --bg-#{$key}, $value);
}

// Generate foreground tokens
@each $key, $value in $theme-fgs {
  $root-tokens: map.set($root-tokens, --fg-#{$key}, $value);
}

// Generate border tokens
@each $key, $value in $theme-borders {
  $root-tokens: map.set($root-tokens, --border-#{$key}, $value);
}

组件 tokens

每个组件定义自己的 token 映射,该映射作为限定到组件类的 CSS 自定义属性输出。这使组件自包含且易于自定义。

以下是提示组件作为示例:

// stylelint-disable-next-line scss/dollar-variable-default
$alert-tokens: defaults(
  (
    --alert-gap: var(--spacer-3),
    --alert-bg: var(--bg-1),
    --alert-padding-x: var(--spacer),
    --alert-padding-y: var(--spacer),
    --alert-color: inherit,
    --alert-border-width: var(--border-width),
    --alert-border-color: var(--border-color),
    --alert-border-radius: var(--radius-7),
    --alert-link-color: inherit,
    --alert-transition-property: "opacity",
    --alert-transition-duration: .15s,
    --alert-transition-timing: linear,
    --hr-border-color: var(--theme-border, var(--alert-border-color)),
  ),
  $alert-tokens
);

这些 tokens 使用 tokens() 混入输出到 .alert 类上:

SCSS
          .alert {
  @include tokens($alert-tokens);

  padding: var(--alert-padding-y) var(--alert-padding-x);
  color: var(--alert-color);
  background-color: var(--alert-bg);
  border: var(--alert-border);
  // ...
}
        

覆盖 Sass tokens

使用 with () 在编译时用 Sass 覆盖特定的组件 token 值。你的覆盖会与默认值合并,因此你只需指定想要更改的键:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" with (
  $alert-tokens: (
    --alert-padding-x: 2rem,
    --alert-bg: var(--bg-2),
    --alert-border-radius: 0,
  )
);
        

这适用于每个组件:$card-tokens、$button-tokens、$menu-tokens、$nav-tokens 等等——任何 $*-tokens 映射都通过相同的合并模式支持部分覆盖。

使用 null 移除 tokens

将任何映射键设置为 null 即可完全移除它。defaults() 函数在映射使用前剔除 null 条目,因此不会为这些键生成 CSS:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" with (
  $alert-tokens: (
    --alert-margin-bottom: null,
  )
);
        

覆盖 CSS tokens

你也可以直接在 CSS 中覆盖 CSS 自定义属性,无需 Sass:

CSS
          .alert {
  --alert-padding-x: 2rem;
  --alert-bg: var(--bg-2);
  --alert-border-radius: 0;
}
        

尺寸映射

除了 token 映射,Bootstrap 还使用尺寸映射来生成尺寸变体类,如 .btn-sm、.btn-lg、.form-control-sm 等。它们使用相同的 defaults() 函数,并支持相同的覆盖和移除模式。

尺寸映射接受一个简单的尺寸名称列表:

SCSS
          $button-sizes: () !default;
$button-sizes: defaults(
  ("xs", "sm", "lg"),
  $button-sizes
);
        

然后循环从每个尺寸名称派生 CSS 自定义属性值:

SCSS
          @each $size, $_ in $button-sizes {
  .btn-#{$size} {
    --btn-min-height: var(--btn-input-#{$size}-min-height);
    --btn-padding-y: var(--btn-input-#{$size}-padding-y);
    // ...
  }
}
        

要移除尺寸,通过 with() 将其键设置为 null:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" with (
  $button-sizes: ("xs": null),
);
        

变体映射

某些组件使用变体映射来生成样式变体。例如,$button-variants 定义 solid、outline、subtle 和 text 按钮样式。这些也由 defaults() 处理并支持 null 移除:

SCSS
          @use "../node_modules/bootstrap/scss/bootstrap" with (
  $button-variants: (
    "text": null,
    "subtle": null,
  ),
);
        

这会从编译后的 CSS 中移除 .btn-text 和 .btn-subtle 类,同时保留 .btn-solid 和 .btn-outline 不变。

必需的键

Bootstrap 假定 Sass 映射中存在一些特定的键,因为我们自己会使用和扩展它们。当你自定义包含的映射时,可能会遇到使用特定 Sass 映射键的错误。

对于 $theme-colors,链接、按钮和表单状态需要 primary、success 和 danger 键。替换这些键的值不应产生任何问题,但移除它们可能导致 Sass 编译问题。

函数

Defaults

defaults() 函数是 Bootstrap 自定义系统的支柱。它将用户覆盖合并到内置默认 tokens 之上,并从结果中剔除任何 null 条目。每个 token 映射、尺寸映射和变体映射都使用它:

SCSS
          @function defaults($defaults, $overrides) { ... }
        

它接受映射或列表作为第一个参数。列表会自动转换为值为 true 的映射,这就是 $button-sizes 等尺寸映射可以使用简洁的 ("xs", "sm", "lg") 语法的方式。

defaults() 通过 tokens() 混入在特定选择器上生成。

颜色对比度

为了满足 Web 内容可访问性指南(WCAG)对比度要求,作者必须提供最低 4.5:1 的文本颜色对比度和最低 3:1 的非文本颜色对比度,极少数例外。

为帮助实现这一点,我们在 Bootstrap 中包含了 color-contrast 函数。它使用 WCAG 对比度比率算法,基于 sRGB 色彩空间中的相对亮度计算对比度阈值,以根据指定的基础颜色自动返回浅色(#fff)、深色(#212529)或黑色(#000)对比色。此函数对于生成多个类的混入或循环特别有用。

例如,从我们的 $theme-colors 映射生成色板:

SCSS
          @each $color, $value in $theme-colors {
  .swatch-#{$color} {
    color: color-contrast(map.get($value, "base"));
  }
}
        

转义 SVG

我们使用 escape-svg 函数为 SVG 背景图片转义 <、> 和 # 字符。使用 escape-svg 函数时,data URI 必须加引号。

SCSS
          // Input — an inline SVG with special characters
$icon: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path fill='none' stroke='#00000080' stroke-width='2' d='m2 5 6 6 6-6'/></svg>");

// After escape-svg(), the <, >, and # characters are percent-encoded
// so the data URI works reliably in CSS (e.g. as a mask-image or background-image)
.element {
  mask-image: escape-svg($icon);
}
        

映射辅助函数

我们包含了若干用于处理映射的 Sass 函数,超出了 Sass 原生提供的功能。

函数描述
map-merge-multiple($maps...)将任意数量的映射合并为一个,从左到右处理它们。
map-get-multiple($map, $values)返回映射的子集,仅筛选出 $values 中列出的键。
map-get-nested($map, $nested-key)从每个嵌套映射条目中提取单个属性,返回扁平映射。

map-merge-multiple($maps...)

SCSS
          @function map-merge-multiple($maps...) { ... }

// Example: combine spacers, negative spacers, and auto into a single values map
values: map-merge-multiple($spacers, $negative-spacers, (auto: auto))
        

map-get-multiple($map, $values)

SCSS
          @function map-get-multiple($map, $values) { ... }

// Example: extract only the flex and order utilities
$utilities: map-get-multiple(
  $utilities,
  ("flex", "flex-direction", "flex-grow", "order")
);
        

map-get-nested($map, $nested-key)

SCSS
          @function map-get-nested($map, $nested-key) { ... }

// Example: pull just the "font-size" value from each entry in $font-sizes
values: map-get-nested($font-sizes, "font-size")
// Returns: ("xs": clamp(...), "sm": clamp(...), ...)
        

negativify-map($map)

通过为每个键添加 n 前缀并取负值,将映射转变为其负值变体。等于 0 的键会被跳过。当自定义工具类需要负值时使用它。

SCSS
          @function negativify-map($map) { ... }

// Example: generate negative values from part of the spacer scale
$custom-spacers: (0: 0, 1: .25rem, 2: .375rem, 3: .5rem);
$negative-spacers: negativify-map($custom-spacers);
// Returns: ("n1": -.25rem, "n2": -.375rem, "n3": -.5rem)
        

主题颜色值

scss/_theme.scss 中的 theme-color-values($key)函数从 $theme-colors 映射的每个条目中提取特定子键,返回颜色名称到值的扁平映射。由于每个主题颜色都是带有 base、text、bg、border 等子键的嵌套映射,此函数可让你一次跨所有颜色提取其中一个子键。它为 _utilities.scss 中大多数颜色相关工具类提供动力:

SCSS
          // In _utilities.scss — generate .focus-ring-{color} classes
"focus-ring": (
  property: --focus-ring-color,
  class: focus-ring,
  values: theme-color-values("focus-ring"),
),

// Merge theme color backgrounds with semantic border tokens for .border-{color} classes
"border-color": (
  property: (
    "--border-color": null,
    "border-color": var(--border-color)
  ),
  class: border,
  values: map.merge(theme-color-values("bg"), $theme-borders),
),
        

主题不透明度值

scss/_theme.scss 中的 theme-opacity-values($color-var, $fallback, $opacities)函数使用 color-mix() 为 CSS 自定义属性生成不透明度变体映射。$opacities 参数默认为 $util-opacity(10 到 100,步长为 10)。在 100 时,它直接返回变量;对于所有其他步长,它将变量与 transparent 混合:

SCSS
          // In _utilities.scss — generate .border-opacity-{n} classes
"border-opacity": (
  class: border-opacity,
  property: border-color,
  values: theme-opacity-values(--bc)
),

// Generate .fg-opacity-{n} classes
"fg-opacity": (
  class: fg-opacity,
  property: color,
  values: theme-opacity-values(--fg)
),
        

混入

我们的 scss/mixins/ 目录包含为 Bootstrap 提供动力的代码片段,也可在你的项目中跨项目使用。

Tokens

tokens() 混入将 Sass 映射输出为 CSS 自定义属性。每个组件都使用它来渲染其 token 映射:

@mixin tokens($map) {
  @each $prop, $value in $map {
    #{$prop}: #{$value};
  }
}
SCSS
          .alert {
  @include tokens($alert-tokens);
  // Outputs: --alert-padding-x: ...; --alert-padding-y: ...; etc.
}
        

颜色方案

prefers-color-scheme 媒体查询提供了一个简写混入,支持 light 和 dark 颜色方案。有关我们颜色模式混入的信息,请参阅颜色模式文档。

@mixin color-scheme($name) {
  @media (prefers-color-scheme: #{$name}) {
    @content;
  }
}
SCSS
          .custom-element {
  @include color-scheme(light) {
    // Insert light mode styles here
  }

  @include color-scheme(dark) {
    // Insert dark mode styles here
  }
}
        

强制颜色

forced-colors: active 媒体查询提供了一个简写混入。当浏览器用系统颜色替换页面颜色时(例如 Windows 高对比度主题),其样式会应用。当 $enable-forced-colors 为 false 时,该混入不输出任何内容。

@mixin forced-colors {
  @if $enable-forced-colors {
    @media (forced-colors: active) {
      @content;
    }
  }
}
SCSS
          .custom-element {
  @include forced-colors() {
    // Insert forced colors styles here
  }
}
        

主题类

generate-theme-classes() 混入遍历 $theme-colors 映射,并为每种颜色输出一个 .theme-* 类。每个类将通用 --theme-* 自定义属性映射到颜色的特定值,因此组件可以引用 --theme-base、--theme-bg 等,并从父级 .theme-* 类获取正确的调色板。它还输出 .theme-reset,将这些 tokens 设置为 initial,以便嵌套组件再次使用自己的默认值:

SCSS
          @include generate-theme-classes();
// Outputs:
// .theme-primary { --theme-base: var(--primary-base); --theme-bg: var(--primary-bg); ... }
// .theme-success { --theme-base: var(--success-base); --theme-bg: var(--success-bg); ... }
// .theme-reset { --theme-base: initial; --theme-bg: initial; ... }
// ...
        
@mixin generate-theme-reset() {
  .theme-reset {
    $keys: ();

    @each $color-map in map.values($theme-colors) {
      @each $key in map.keys($color-map) {
        $keys: map.merge($keys, ($key: true));
      }
    }

    @each $key in map.keys($keys) {
      --theme-#{$key}: initial;
    }
  }
}

遮罩图标

mask-icon() 混入通过 CSS mask 渲染 SVG 图标,以便使用元素的 background-color 绘制形状。这使图标能够继承当前文本颜色,从而无需单独的 SVG 即可实现自动深色模式。我们将其用于关闭按钮、导航栏切换器、复选框标记、面包屑分隔符、日期选择器箭头和轮播控件。

某些表单控件无法使用 mask,因为它们不支持伪元素,并且遮罩会裁剪整个字段。<select> 箭头以及使用 .form-control-caret 的输入是两个例子,它们改为保留单独的浅色和深色 background-image SVG 作为非遮罩背景图片。

@mixin mask-icon($icon: null, $size: contain, $position: center) {
  @if $icon != null {
    mask-image: $icon;
  }
  mask-repeat: no-repeat;
  @if $position != null {
    mask-position: $position;
  }
  @if $size != null {
    mask-size: $size;
  }
}

自行在元素上设置 background-color(混入只输出 mask-* 属性),然后将你的图标作为遮罩图片传入。当图标有条件应用时(例如按状态或方向),为图标传入 null。

SCSS
          .custom-icon {
  // Declare a custom CSS variable for the icon. This could be on the same
  // element, `:root`, or a parent element. We're using a custom × icon. Be
  // sure to wrap in `escape-svg()` as well.
  --custom-icon: #{escape-svg(url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path fill='none' stroke='black' stroke-linecap='round' stroke-width='2' d='m4 4 8 8m0-8-8 8'/></svg>"))};

  width: 1rem;
  height: 1rem;
  background-color: currentcolor;
  @include mask-icon($icon: var(--custom-icon));
}