Skip to main content Skip to docs navigation

Sass

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

利用我们的源 Sass 文件来利用变量、映射、混合等。

¥Utilize our source Sass files to take advantage of variables, maps, mixins, and more.

文件结构

¥File structure

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

¥Whenever possible, avoid modifying Bootstrap’s core files. For Sass, that means creating your own stylesheet that imports Bootstrap so you can modify and extend it. Assuming you’re using a package manager like npm, you’ll have a file structure that looks like this:

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

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

¥If you’ve downloaded our source files and aren’t using a package manager, you’ll want to manually create something similar to that structure, keeping Bootstrap’s source files separate from your own.

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

输入

¥Importing

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

¥In your custom.scss, you’ll import Bootstrap’s source Sass files. You have two options: include all of Bootstrap, or pick the parts you need. We encourage the latter, though be aware there are some requirements and dependencies across our components. You also will need to include some JavaScript for our plugins.

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

// Include any default variable overrides here (though functions won't be available)

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

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

// 1. Include functions first (so you can manipulate colors, SVGs, calc, etc)
@import "../node_modules/bootstrap/scss/functions";

// 2. Include any default variable overrides here

// 3. Include remainder of required Bootstrap stylesheets (including any separate color mode stylesheets)
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/variables-dark";

// 4. Include any default map overrides here

// 5. Include remainder of required parts
@import "../node_modules/bootstrap/scss/maps";
@import "../node_modules/bootstrap/scss/mixins";
@import "../node_modules/bootstrap/scss/root";

// 6. Optionally include any other parts as needed
@import "../node_modules/bootstrap/scss/utilities";
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
@import "../node_modules/bootstrap/scss/images";
@import "../node_modules/bootstrap/scss/containers";
@import "../node_modules/bootstrap/scss/grid";
@import "../node_modules/bootstrap/scss/helpers";

// 7. Optionally include utilities API last to generate classes based on the Sass map in `_utilities.scss`
@import "../node_modules/bootstrap/scss/utilities/api";

// 8. Add additional custom code here

完成该设置后,你可以开始修改 custom.scss 中的任何 Sass 变量和映射。你还可以根据需要开始在 // Optional 部分下添加 Bootstrap 的部分内容。我们建议使用 bootstrap.scss 文件中的完整导入堆栈作为起点。

¥With that setup in place, you can begin to modify any of the Sass variables and maps in your custom.scss. You can also start to add parts of Bootstrap under the // Optional section as needed. We suggest using the full import stack from our bootstrap.scss file as your starting point.

编译

¥Compiling

为了在浏览器中使用自定义 Sass 代码作为 CSS,你需要一个 Sass 编译器。Sass 作为 CLI 包提供,但你也可以使用其他构建工具(如 GulpWebpack)或 GUI 应用来编译它。一些 IDE 还内置了 Sass 编译器或作为可下载的扩展。

¥In order to use your custom Sass code as CSS in the browser, you need a Sass compiler. Sass ships as a CLI package, but you can also compile it with other build tools like Gulp or Webpack, or with a GUI applications. Some IDEs also have Sass compilers built in or as downloadable extensions.

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

¥We like to use the CLI to compile our Sass, but you can use whichever method you prefer. From the command line, run the following:

# 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 进行编译 了解有关你的选择的更多信息。

¥Learn more about your options at sass-lang.com/install and compiling with VS Code.

Using Bootstrap with another build tool? Consider reading our guides for compiling with Webpack, Parcel, or Vite. We also have production-ready demos in our examples repository on GitHub.

包括

¥Including

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

¥Once your CSS is compiled, you can include it in your HTML files. Inside your index.html you’ll want to include your compiled CSS file. Be sure to update the path to your compiled CSS file if you’ve changed it.

<!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>

变量默认值

¥Variable defaults

Bootstrap 中的每个 Sass 变量都包含 !default 标志,允许你在自己的 Sass 中覆盖变量的默认值,而无需修改 Bootstrap 的源代码。根据需要复制并粘贴变量,修改其值,并删除 !default 标志。如果一个变量已经被赋值,那么它不会被 Bootstrap 中的默认值重新赋值。

¥Every Sass variable in Bootstrap includes the !default flag allowing you to override the variable’s default value in your own Sass without modifying Bootstrap’s source code. Copy and paste variables as needed, modify their values, and remove the !default flag. If a variable has already been assigned, then it won’t be re-assigned by the default values in Bootstrap.

你将在 scss/_variables.scss 中找到 Bootstrap 变量的完整列表。某些变量设置为 null,这些变量不会输出属性,除非它们在你的配置中被覆盖。

¥You will find the complete list of Bootstrap’s variables in scss/_variables.scss. Some variables are set to null, these variables don’t output the property unless they are overridden in your configuration.

变量覆盖必须在函数导入之后、其余导入之前进行。

¥Variable overrides must come after our functions are imported, but before the rest of the imports.

下面是一个在通过 npm 导入和编译 Bootstrap 时将 background-colorcolor 更改为 <body> 的示例:

¥Here’s an example that changes the background-color and color for the <body> when importing and compiling Bootstrap via npm:

// Required
@import "../node_modules/bootstrap/scss/functions";

// Default variable overrides
$body-bg: #000;
$body-color: #111;

// Required
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/variables-dark";
@import "../node_modules/bootstrap/scss/maps";
@import "../node_modules/bootstrap/scss/mixins";
@import "../node_modules/bootstrap/scss/root";

// Optional Bootstrap components here
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
// etc

根据需要对 Bootstrap 中的任何变量重复此操作,包括下面的全局选项。

¥Repeat as necessary for any variable in Bootstrap, including the global options below.

Get started with Bootstrap via npm with our starter project! Head to the Sass & JS example template repository to see how to build and customize Bootstrap in your own npm project. Includes Sass compiler, Autoprefixer, Stylelint, PurgeCSS, and Bootstrap Icons.

映射和循环

¥Maps and loops

Bootstrap 包含一些 Sass 映射、键值对,可以更轻松地生成相关 CSS 系列。我们使用 Sass 映射来表示颜色、网格断点等。就像 Sass 变量一样,所有 Sass 映射都包含 !default 标志,并且可以覆盖和扩展。

¥Bootstrap includes a handful of Sass maps, key value pairs that make it easier to generate families of related CSS. We use Sass maps for our colors, grid breakpoints, and more. Just like Sass variables, all Sass maps include the !default flag and can be overridden and extended.

默认情况下,我们的一些 Sass 映射会合并为空映射。这样做是为了方便地扩展给定的 Sass 映射,但代价是使从映射中删除项目变得稍微困难一些。

¥Some of our Sass maps are merged into empty ones by default. This is done to allow easy expansion of a given Sass map, but comes at the cost of making removing items from a map slightly more difficult.

修改映射

¥Modify map

$theme-colors 映射中的所有变量都定义为独立变量。要修改 $theme-colors 映射中的现有颜色,请将以下内容添加到你的自定义 Sass 文件中:

¥All variables in the $theme-colors map are defined as standalone variables. To modify an existing color in our $theme-colors map, add the following to your custom Sass file:

$primary: #0074d9;
$danger: #ff4136;

随后,这些变量在 Bootstrap 的 $theme-colors 映射中设置:

¥Later on, these variables are set in Bootstrap’s $theme-colors map:

$theme-colors: (
  "primary": $primary,
  "danger": $danger
);

添加到映射

¥Add to map

通过使用自定义值创建新的 Sass 映射并将其与原始映射合并,向 $theme-colors 或任何其他映射添加新颜色。在本例中,我们将创建一个新的 $custom-colors 映射并将其与 $theme-colors 合并。

¥Add new colors to $theme-colors, or any other map, by creating a new Sass map with your custom values and merging it with the original map. In this case, we’ll create a new $custom-colors map and merge it with $theme-colors.

// Create your own map
$custom-colors: (
  "custom-color": #900
);

// Merge the maps
$theme-colors: map-merge($theme-colors, $custom-colors);

从映射中删除

¥Remove from map

要从 $theme-colors 或任何其他贴图中删除颜色,请使用 map-remove。请注意,你必须在 variables 中的定义之后和 maps 中的使用之前插入 $theme-colors

¥To remove colors from $theme-colors, or any other map, use map-remove. Be aware you must insert $theme-colors between our requirements just after its definition in variables and before its usage in maps:

// Required
@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/variables-dark";

$theme-colors: map-remove($theme-colors, "info", "light", "dark");

@import "../node_modules/bootstrap/scss/maps";
@import "../node_modules/bootstrap/scss/mixins";
@import "../node_modules/bootstrap/scss/root";

// Optional
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
// etc

所需按键

¥Required keys

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

¥Bootstrap assumes the presence of some specific keys within Sass maps as we used and extend these ourselves. As you customize the included maps, you may encounter errors where a specific Sass map’s key is being used.

例如,我们使用 $theme-colors 中的 primarysuccessdanger 键来表示链接、按钮和表单状态。替换这些键的值应该不会出现问题,但删除它们可能会导致 Sass 编译问题。在这些情况下,你需要修改使用这些值的 Sass 代码。

¥For example, we use the primary, success, and danger keys from $theme-colors for links, buttons, and form states. Replacing the values of these keys should present no issues, but removing them may cause Sass compilation issues. In these instances, you’ll need to modify the Sass code that makes use of those values.

函数

¥Functions

颜色

¥Colors

除了我们拥有的 Sass 映射 之外,主题颜色也可以用作独立变量,例如 $primary

¥Next to the Sass maps we have, theme colors can also be used as standalone variables, like $primary.

.custom-element {
  color: $gray-100;
  background-color: $dark;
}

你可以使用 Bootstrap 的 tint-color()shade-color() 函数使颜色变亮或变暗。这些函数会将颜色与黑色或白色混合,这与 Sass 的原生 lighten()darken() 函数不同,后者会按固定量改变亮度,这通常不会产生所需的效果。

¥You can lighten or darken colors with Bootstrap’s tint-color() and shade-color() functions. These functions will mix colors with black or white, unlike Sass’ native lighten() and darken() functions which will change the lightness by a fixed amount, which often doesn’t lead to the desired effect.

shift-color() 结合了这两个功能,如果权重为正,则对颜色进行着色;如果权重为负,则对颜色进行着色。

¥shift-color() combines these two functions by shading the color if the weight is positive and tinting the color if the weight is negative.

// Tint a color: mix a color with white
@function tint-color($color, $weight) {
  @return mix(white, $color, $weight);
}

// Shade a color: mix a color with black
@function shade-color($color, $weight) {
  @return mix(black, $color, $weight);
}

// Shade the color if the weight is positive, else tint it
@function shift-color($color, $weight) {
  @return if($weight > 0, shade-color($color, $weight), tint-color($color, -$weight));
}

在实践中,你可以调用该函数并传入颜色和重量参数。

¥In practice, you’d call the function and pass in the color and weight parameters.

.custom-element {
  color: tint-color($primary, 10%);
}

.custom-element-2 {
  color: shade-color($danger, 30%);
}

.custom-element-3 {
  color: shift-color($success, 40%);
  background-color: shift-color($success, -60%);
}

色彩对比

¥Color contrast

为了满足 网页内容无障碍指南 (WCAG) 对比度要求,作者必须提供最低 文本颜色对比度为 4.5:1 和最低 非文本颜色对比度为 3:1,极少数例外。

¥In order to meet the Web Content Accessibility Guidelines (WCAG) contrast requirements, authors must provide a minimum text color contrast of 4.5:1 and a minimum non-text color contrast of 3:1, with very few exceptions.

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

¥To help with this, we included the color-contrast function in Bootstrap. It uses the WCAG contrast ratio algorithm for calculating contrast thresholds based on relative luminance in an sRGB color space to automatically return a light (#fff), dark (#212529) or black (#000) contrast color based on the specified base color. This function is especially useful for mixins or loops where you’re generating multiple classes.

例如,要从 $theme-colors 贴图生成颜色样本:

¥For example, to generate color swatches from our $theme-colors map:

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

它还可以用于一次性对比需求:

¥It can also be used for one-off contrast needs:

.custom-element {
  color: color-contrast(#000); // returns `color: #fff`
}

你还可以使用我们的颜色图函数指定基色:

¥You can also specify a base color with our color map functions:

.custom-element {
  color: color-contrast($dark); // returns `color: #fff`
}

转义 SVG

¥Escape SVG

我们使用 escape-svg 函数对 SVG 背景图片的 <># 字符进行转义。使用 escape-svg 函数时,必须引用数据 URI。

¥We use the escape-svg function to escape the <, > and # characters for SVG background images. When using the escape-svg function, data URIs must be quoted.

加法和减法函数

¥Add and Subtract functions

我们使用 addsubtract 函数来封装 CSS calc 函数。这些函数的主要目的是避免将 “unitless” 0 值传递到 calc 表达式时出现错误。像 calc(10px - 0) 这样的表达式将在所有浏览器中返回错误,尽管在数学上是正确的。

¥We use the add and subtract functions to wrap the CSS calc function. The primary purpose of these functions is to avoid errors when a “unitless” 0 value is passed into a calc expression. Expressions like calc(10px - 0) will return an error in all browsers, despite being mathematically correct.

计算有效的示例:

¥Example where the calc is valid:

$border-radius: .25rem;
$border-width: 1px;

.element {
  // Output calc(.25rem - 1px) is valid
  border-radius: calc($border-radius - $border-width);
}

.element {
  // Output the same calc(.25rem - 1px) as above
  border-radius: subtract($border-radius, $border-width);
}

计算无效的示例:

¥Example where the calc is invalid:

$border-radius: .25rem;
$border-width: 0;

.element {
  // Output calc(.25rem - 0) is invalid
  border-radius: calc($border-radius - $border-width);
}

.element {
  // Output .25rem
  border-radius: subtract($border-radius, $border-width);
}

混入

¥Mixins

我们的 scss/mixins/ 目录有大量的 mixin,它们为 Bootstrap 的各个部分提供支持,也可以在你自己的项目中使用。

¥Our scss/mixins/ directory has a ton of mixins that power parts of Bootstrap and can also be used across your own project.

配色方案

¥Color schemes

prefers-color-scheme 媒体查询的简写 mixin 可用,支持 lightdark 配色方案。有关我们的颜色模式混合的信息,请参阅颜色模式文档

¥A shorthand mixin for the prefers-color-scheme media query is available with support for light and dark color schemes. See the color modes documentation for information on our color mode mixin.

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

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