Use Bootstrap's utility API from my scss file

Viewed 226

The Bootstrap docs explain 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. 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 fails.

2 Answers

You have to set BS5 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

@YaroslavTrach's answer is CORRECT.

But until he explained how to do it properly, I was using a workaround. I'm adding it here for those who don't use scss, or don't have a node-based build environment in their project.

I added the regular mt-1 etc. classes to my custom css, and modified their names and values:

.mt-n1 { margin-top: -0.25rem !important; }
.mt-n2 { margin-top: -0.5rem !important; }
.mt-n3 { margin-top: -1rem !important; }
.mt-n4 { margin-top: -1.5rem !important; }
.mt-n5 { margin-top: -3rem !important; }

But if you do have a node-based build environment for your frontend, I recommend the accepted answer as it adds classes for every breakpoint.

Related