Search code examples
twitter-bootstrapsassbootstrap-5scss-mixins

Use Bootstrap's utility API from my SCSS file


The Bootstrap documentation explains how to enable negative margins, but that is for the case where one customises Bootstrap.

I'm using it from a CDN, but I still want those classes (e.g., mt-n1). I'd like to import them via a mixin (or something like that) into my SCSS file. The "Utility API" shows that is possible, but I'm unsure how to invoke it from my SCSS file.

How do I do that?

For example:

// Import bootstrap
@import "~bootstrap/scss/functions";
@import "~bootstrap/scss/variables";
@import "~bootstrap/scss/mixins";
@import "~bootstrap/scss/utilities";

// Generate negative margin from $utilities:"negative-margin"
// ... <--- What goes here?

I tried @include generate-utility("negative-margin") but that failed.


Solution

  • You have to set the Bootstrap 5 variable $enable-negative-margins to true and insert it before variables.scss include.

    Then, remove all utilities, and include only ones you want, see example:

    // Enabling negative margins
    $enable-negative-margins: true;
    
    @import "~bootstrap/scss/functions";
    @import "~bootstrap/scss/variables";
    @import "~bootstrap/scss/mixins";
    @import "~bootstrap/scss/utilities";
    
    // Remove all utilities and include only what you want
    $utilities: (
      (
        "negative-margin": map-get($utilities, "negative-margin"),
        "negative-margin-x": map-get($utilities, "negative-margin-x"),
        "negative-margin-y": map-get($utilities, "negative-margin-y"),
        "negative-margin-top": map-get($utilities, "negative-margin-top"),
        "negative-margin-end": map-get($utilities, "negative-margin-end"),
        "negative-margin-bottom": map-get($utilities, "negative-margin-bottom"),
        "negative-margin-start": map-get($utilities, "negative-margin-start"),
      )
    );
    
    // Generate utilities
    @import "bootstrap/scss/utilities/api";
    

    Output:

    Enter image description here