Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 58 ยท Customizing

Customizing with Sass

Compile Bootstrap from Sass: override variable defaults, add theme colors with map-merge, import only the parts you need and ship a smaller custom CSS file.

CSS variables (the previous lesson) change how the finished stylesheet looks. Sass changes how that stylesheet is made. Bootstrap's source is a set of Sass files full of variables, maps and small functions. If you compile those files yourself, you can change a color once and have every hover shade, alert tint and button text color recalculated, add your own theme color that gets a whole family of classes, and leave out the components you never use.

The live editor on this site has no Sass compiler, so the setup and the Sass files in this lesson are read-only code. The TryIts show the idea in a way that does run: a small JavaScript copy of Bootstrap's color math, and hand-written CSS that imitates what a compile produces. The commands and imports are the real ones for Bootstrap 5.3.

What you need

A Sass build needs Node.js and two packages. In a project folder:

Terminal
npm init -y
npm install bootstrap@5.3.3 sass

Bootstrap's Sass source is then in node_modules/bootstrap/scss/. Create a folder for your own file, for example scss/custom.scss, and add a script to package.json that compiles it:

JSON
{
  "scripts": {
    "css": "sass --load-path=node_modules scss/custom.scss dist/custom.css --style=compressed"
  }
}

--load-path=node_modules lets you write @import "bootstrap/scss/functions" instead of a long relative path. Run npm run css and the compiled file appears in dist/. You then link dist/custom.css instead of the CDN stylesheet, never in addition to it.

About @import. Bootstrap 5.3 is written with Sass's @import rule. Current Sass versions print a deprecation warning for it, because Sass is moving toward @use. The build still works. Bootstrap 5 has no @use entry point, so for now you keep @import and either ignore the warnings or silence them with the options your Sass version documents (for example --quiet-deps).

The one rule: order of imports

Sass variables in Bootstrap are declared with the !default flag. That flag means "set this only if it has no value yet". So your values must be defined before Bootstrap's variables file is imported, and Bootstrap then leaves them alone.

SCSS
// 1. Functions first: you may use them in your own overrides
@import "bootstrap/scss/functions";

// 2. YOUR variable overrides go here, before the variables file
$primary: #7c3aed;
$enable-shadows: true;
$border-radius: 0.5rem;
$font-family-sans-serif: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;

// 3. Bootstrap's own variables, maps and mixins
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/utilities";

// 4. The parts that produce CSS
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/buttons";
// ...more components...
@import "bootstrap/scss/helpers";
@import "bootstrap/scss/utilities/api";

If you set $primary after @import "bootstrap/scss/variables", nothing happens, because the default already won. This is the most common Sass mistake with Bootstrap.

flowchart LR
  F["functions"] --> O["Your overrides<br/>$primary, $border-radius"]
  O --> V["variables<br/>(!default skips yours)"]
  V --> M["maps and mixins"]
  M --> C["components, helpers"]
  C --> U["utilities/api"]
  U --> OUT["custom.css"]

Overrides sit between functions and variables; later partials read the final values.

Variables worth knowing

You rarely need many. These cover most real projects:

Variable Effect
$primary, $secondary, $success, $info, $warning, $danger The theme colors and everything derived from them
$body-bg, $body-color Page background and text color
$font-family-sans-serif, $font-size-base, $line-height-base Typography
$border-radius, $border-radius-sm, $border-radius-lg Rounded corners
$spacer The base of the spacing scale (1rem by default; the scale is a map built from it)
$enable-rounded, $enable-shadows, $enable-gradients, $enable-transitions Switch whole features on or off
$enable-dark-mode Whether the color-mode styles are generated (covered in the dark mode lesson)
$enable-cssgrid Add the opt-in CSS Grid layout beside the flexbox grid
$min-contrast-ratio The contrast target used when Bootstrap picks text colors

Because everything is derived, one line such as $primary: #7c3aed; produces a whole family: .btn-primary and .btn-outline-primary with matching hover and active shades, .alert-primary, .text-primary, .bg-primary-subtle, focus rings and more. You will not write any of those by hand.

How the shades are calculated

Sass does the color math at compile time. Hover and active shades are mixes of the base color with black (a shade) or white (a tint), and the text color on a button is chosen by a contrast check. This script is a plain JavaScript version of the same idea. It reproduces the default blue button values you can find in Bootstrap's own CSS (#0b5ed7, #0a58ca, #0a53be) and then applies the math to a new purple.

JS Bootstrap's color math, in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line of output matches Bootstrap's stock .btn-primary (hover #0b5ed7, active #0a58ca). The yellow gets black text and lighter hover states, exactly like .btn-warning (#ffca2c on hover, #ffcd39 when active), because white on #ffc107 has a contrast ratio of only about 1.6. Bootstrap darkens dark colors and lightens light ones, so the hover effect stays visible. When you change $primary, Sass runs this logic for you, which is why a light brand color automatically gets dark button text.

Adding your own theme color with map-merge

Theme colors live in a Sass map called $theme-colors. To add a new one, merge into the map after the variables file and before the maps file, because maps derives other maps from it:

SCSS
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";

$brand: #7c3aed;
$theme-colors: map-merge(
  $theme-colors,
  (
    "brand": $brand
  )
);

@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/utilities";
// ...rest as before

After the compile, .btn-brand, .btn-outline-brand, .bg-brand, .text-brand, .border-brand, .alert-brand, .badge and list-group variants for brand all exist, with shades and contrast handled. You can remove a color the same way: map-remove($theme-colors, "info").

You can see what such a compile gives you. The next example is hand-written CSS that imitates the generated classes, using the numbers from the script above.

What a 'brand' theme color produces (stand-in CSS)

In a real build you would write none of this CSS. The point is that the shape of the output is ordinary Bootstrap component variables, the same ones you tuned by hand in the previous lesson.

Building a lean bundle

The full bootstrap.min.css from the CDN weighs about 230 KB uncompressed (roughly 30 KB gzipped). A real page rarely uses every component. With Sass you choose what to import, so unused parts never reach the file.

The required core is: functions, variables, variables-dark, maps, mixins, utilities, then root and reboot. After that, import only what you use:

SCSS
// Layout and content
@import "bootstrap/scss/containers";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/type";
@import "bootstrap/scss/images";

// Only the components this site shows
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/card";
@import "bootstrap/scss/navbar";
@import "bootstrap/scss/nav";
@import "bootstrap/scss/transitions";   // needed for collapse and fade
@import "bootstrap/scss/close";         // used by alerts, modals, toasts

// Helpers and the generated utilities, always last
@import "bootstrap/scss/helpers";
@import "bootstrap/scss/utilities/api";

Some partials depend on others, and the compiler tells you when you skipped one (an "undefined variable" or "no mixin named" error). The navbar, for example, builds on nav, and the collapse behaviour needs transitions. Add the missing partial and recompile.

The same idea applies to JavaScript. With a bundler (Vite, webpack, esbuild) you import only the plugins you use. A bundler can then leave the rest out, which is called tree-shaking:

JavaScript
// Only these two plugins end up in your bundle
import { Collapse, Modal } from 'bootstrap';

or import a single plugin file directly: import Modal from 'bootstrap/js/dist/modal';. The plugins that use popups (dropdowns, tooltips, popovers) need Popper, which npm installs as a peer dependency.

flowchart TD
  FULL["Full Bootstrap CSS<br/>about 230 KB"] --> CHOOSE{"Choose partials"}
  CHOOSE -->|"core + grid + buttons + card"| LEAN["Lean custom.css<br/>noticeably smaller"]
  CHOOSE -->|"everything"| FULL2["Same size as the CDN file"]

The savings come from what you leave out, not from the compression.

Fewer partials means fewer classes. If you drop forms and later write class="form-control", nothing happens and no error appears in the browser. Keep a short comment above each import saying which page needs it, and test the real pages after every change.

Changing maps: spacers, breakpoints and utilities

Some customizations are maps, not single values. The spacing scale is $spacers, the breakpoints are $grid-breakpoints, and the utilities are $utilities (see The Utility API). Merge into a map to add to it:

SCSS
$spacers: map-merge(
  $spacers,
  (
    6: $spacer * 4,   // adds .m-6, .p-6, .gap-6 ...
  )
);

Replacing $grid-breakpoints or $container-max-widths is possible, but they must stay in matching pairs and be consistent, so change them rarely and test the layout on every width.

A new spacing step, imitated

Component variables: accordion, alert, badge, breadcrumb and forms

Besides the global variables, every component has its own set, named $component-property. They are the way to restyle one component everywhere without writing override CSS. Four components in Bootstrap 5.3 also expose the same values as CSS variables on the component's own class (--bs-accordion-bg, --bs-alert-padding-x, ...), which lets you change them at run time, on one element, with no build step. Form controls do not have CSS variables; they are Sass-only.

Component Common Sass variables (all !default) What they control
Accordion $accordion-padding-y, $accordion-padding-x, $accordion-color, $accordion-bg, $accordion-border-width, $accordion-border-color, $accordion-border-radius the panel box
$accordion-body-padding-y/x, $accordion-button-padding-y/x spacing inside the body and the header button
$accordion-button-color, $accordion-button-bg, $accordion-button-active-bg, $accordion-button-active-color, $accordion-button-focus-box-shadow the header button in its normal, open and focused states
$accordion-icon-width, $accordion-icon-color, $accordion-icon-active-color, $accordion-icon-transition, $accordion-icon-transform the chevron icon and how it turns
Alert $alert-padding-y, $alert-padding-x, $alert-margin-bottom, $alert-border-radius, $alert-link-font-weight, $alert-border-width, $alert-dismissible-padding-r spacing, shape and the room kept for the close button
$alert-bg-scale, $alert-border-scale, $alert-color-scale how colors are derived from the theme color (deprecated since 5.2; the subtle colors replace them)
Badge $badge-font-size, $badge-font-weight, $badge-color, $badge-padding-y, $badge-padding-x, $badge-border-radius size, weight and shape
Breadcrumb $breadcrumb-font-size, $breadcrumb-padding-y/x, $breadcrumb-item-padding-x, $breadcrumb-margin-bottom, $breadcrumb-bg, $breadcrumb-border-radius the bar
$breadcrumb-divider, $breadcrumb-divider-color, $breadcrumb-divider-flipped, $breadcrumb-active-color the separator (/ by default; the flipped one is used in right-to-left pages) and the current item

Forms are the largest group. The most used ones:

Group Variables
Text inputs $input-padding-y, $input-padding-x, $input-font-family, $input-font-size, $input-line-height, $input-color, $input-bg, $input-border-width, $input-border-color, $input-border-radius
Sizes $input-padding-y-sm, $input-padding-x-sm, $input-font-size-sm, $input-border-radius-sm, and the same with -lg
Disabled $input-disabled-bg, $input-disabled-border-color, $input-disabled-color
Focus $input-focus-bg, $input-focus-color, $input-focus-border-color, $input-focus-box-shadow
Placeholder $input-placeholder-color
Labels and help $form-label-font-size, $form-label-font-weight, $form-label-color, $form-text-font-size, $form-text-color
File input $form-file-button-color, $form-file-button-bg, $form-file-button-hover-bg
Select $form-select-padding-y, $form-select-padding-x, $form-select-font-size, $form-select-color, $form-select-bg, $form-select-border-width, $form-select-border-color, $form-select-border-radius, $form-select-indicator-padding, $form-select-indicator-color, $form-select-focus-border-color, $form-select-focus-box-shadow, $form-select-transition, and -sm / -lg versions of padding and font size

A form-focused override, set before the Bootstrap imports like any other variable (see the import-order rule above):

SCSS
$input-border-radius: 0.75rem;
$input-border-color: #94a3b8;
$input-focus-border-color: #6366f1;
$input-focus-box-shadow: 0 0 0 0.2rem rgba(99, 102, 241, 0.25);
$form-select-indicator-color: #334155;
$accordion-button-active-bg: #eef2ff;
$badge-font-weight: 500;
$breadcrumb-divider: quote("โ€บ");

Most $form-select-* variables are defined as $input-* values with !default, so an override of $input-border-radius carries over to selects automatically (your overrides are read first, then Bootstrap fills in the rest). Set a $form-select-* variable only when selects should differ from text inputs.

The runtime route: component CSS variables

Without a build step you can change the same properties from CSS. Set the variable on the component, or on a wrapper if you want it to apply to a whole section:

Restyling components with their CSS variables

The wrapper class indigo-theme has the same specificity trick as any scoped override: your selector (.indigo-theme .alert) is more specific than Bootstrap's .alert, so it wins regardless of load order. Use whichever route matches your project: Sass variables when you build Bootstrap yourself and want the change baked in, CSS variables when you load the ready-made file and want per-page or per-section changes.

Variable names can change between minor versions. The lists above match Bootstrap 5.3.3. Before you upgrade, search the new scss/_variables.scss for each name you override; Sass reports an error for a removed mixin or function, but a variable you set that no longer exists is silently ignored.

A sensible Sass workflow

  1. Keep one entry file (custom.scss) and never edit files inside node_modules.
  2. Group your overrides in one block above the variables import, with a short comment for each.
  3. Commit the Bootstrap version in package.json (an exact number, such as 5.3.3), so a rebuild next year gives the same result.
  4. Compile in CI or a build script, and publish only the compressed output.
  5. When you upgrade Bootstrap, read the release notes and recompile; most variable names stay stable inside 5.3.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must your variable overrides come before the import of bootstrap/scss/variables?

    !default means 'assign only if not already defined'. Set $primary after the import and Bootstrap's default has already won.
  2. 2. Where do you merge a new color into $theme-colors?

    The maps partial derives other maps (such as the RGB versions) from $theme-colors, so the merge must happen before it.
  3. 3. What is the benefit of changing $primary in Sass compared with a CSS variable?

    Sass runs the shade, tint and contrast functions at compile time, so the whole family of derived colors follows one value.
  4. 4. How do you get a smaller CSS file from the Sass source?

    Components you do not import produce no CSS. Keep the core partials and add the parts the pages need.
  5. 5. You compile your own CSS. How do you link it?

    Your compiled file already contains Bootstrap. Loading both doubles the CSS and can make the CDN rules override yours.

Summary

  • Sass lets you rebuild Bootstrap: install bootstrap and sass with npm, compile your own entry file with --load-path=node_modules.
  • Override variables before importing bootstrap/scss/variables; Bootstrap's !default values yield to yours.
  • A single color change regenerates hover, active, subtle and text colors through shade, tint and contrast functions.
  • Add theme colors with map-merge on $theme-colors before the maps import; extend $spacers and $utilities the same way.
  • Import only the partials (and JavaScript plugins) you need to produce a lean bundle; the compiler reports missing dependencies.
  • Sass code in this lesson is read-only here; the TryIts use JavaScript and hand-written CSS to show the same results.

Next lesson: Color Modes and Dark Mode.