Bootstrap 4 SCSS overrides not working

2019-06-23 22:19发布

问题:

So here is a quote from the Bootstrap docs:

Every Sass variable in Bootstrap 4 includes the !default flag, meaning you can override that default value in your own Sass even after that original variable’s been defined.

Below is my theme.scss file content:

// Bootstrap original
@import "bootstrap/scss/bootstrap";

// Variables overrides
@import "custom-variables";

The content of the custom custom-variables.scss file (to test only):

$body-color: #555;
$font-family-base: serif;

Everything compiles OK, however with no changes to the styles (e.g. the body color and base font family remains the same as it is in the original Bootstrap files. Howe come?

回答1:

For v4 alpha. The thing is that you need to override the variables before they get applied to all the boostrap styles (currently you do it afterwards). In bootstrap/scss/bootstrap every scss file gets imported, starting with their variables file. Right after this they provide a kind of hook for you to override the variables before they are used for tables, buttons and so on.

Bootstrap 4 ships with a _custom.scss file for easy overriding of default variables in /scss/_variables.scss. Copy and paste relevant lines from there into the _custom.scss file, modify the values, and recompile your Sass to change our default values. Be sure to remove the !default flag from override values. [Source]

The _custom.scss file should be located inside of your bootstrap/scss/ directory.
Note: this is deprecated since v4 beta.


For v4 beta and above. Variable defaults basically work the other way around. A variable with !default flag will default to the previously set value of this variable (if any available). As all bootstrap variables have this flag, you could import your custom-variables.scss before the bootstrap/scss/bootstrap;

$var: 2px; /* set in custom-variables.scss */
$var: 1px !default; /* set in the bootstrap _variables.scss */

.element {
  width: $var;
}

compiles to

.element {
  width: 2px;
}

A way to use bootstrap variables when overriding them is to import the _variables.scss file twice; once as a single file before you define your overrides and once after as part of whole bootstrap:

// @import bootstrap _variables.scss file
$var: 1px !default;
$var2: 4px !default;

// your custom-variables.scss
$var: 2px + $var2;

// @import bootstrap
$var: 1px !default;
$var2: 4px !default;

.element {
  width: $var;
}

compiles to

.element {
  width: 6px;
}