Skip to content

Instantly share code, notes, and snippets.

@NekitoSP
Forked from passcod/__why-and-how-to-use.md
Created November 20, 2019 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NekitoSP/30ca8e4c0f17965ea4233a4e22721917 to your computer and use it in GitHub Desktop.
Save NekitoSP/30ca8e4c0f17965ea4233a4e22721917 to your computer and use it in GitHub Desktop.
Bootstrap 4 mixins for spacing utilities without classes

Why?

This:

.action {
  @extend .ml-3;
}

will generate the equivalent to this:

.action {
  margin-left: 1rem !important;
}

Ahhh, !important!!1 Noooo

There must be a better way:

.action {
  @include ml(3);
}

Makes:

.action {
  margin-left: 1rem;
}

This therefore gets you not-!important, convenient access to the Bootstrap 4 sizings, with a clear path to extraction of inline classes into css. But there are other goodies:

Negative standard sizings

For negative margins of the standard sizes:

@include mr(-2);
margin-right: -0.5rem;

The X and Y conveniences

To set two ends at once without setting the others:

@include px(3);
padding-left: 1rem;
padding-right: 1rem;

Arbitrary sizes

Most useful with the X/Y conveniences, but good with the rest as well:

@include my(2.3em);
@include p(3vh);
margin-top: 2.3em;
margin-bottom: 2.3em;
padding: 3vh;

Auto works as well

@include ml(auto);
margin-left: auto;

A simple function for more complex sass

Useful in calculations or to use standard sizings in other properties. bsize is for "bootstrap size".

border-width: bsize(2);
border-width: 0.5rem;

Does not include: breakpoint variants

Because you should just use the @include media-breakpoint-{up,down,etc} utilities.

@function map-get-or-key($map, $key) {
@if map-has-key($map, $key) or map-has-key($map, -$key) {
@if $key != 'auto' and type-of($key) == 'number' and $key < 0 {
@return 0 - map-get($map, -$key);
} @else {
@return map-get($map, $key);
}
} @else if type-of($key) == 'string' {
@return unquote($key);
} @else {
@return $key;
}
}
@function bsize($key) {
@return map-get-or-key($spacers, $key);
}
@mixin m($space) {
margin: bsize($space);
}
@mixin mt($space) {
margin-top: bsize($space);
}
@mixin mb($space) {
margin-bottom: bsize($space);
}
@mixin ml($space) {
margin-left: bsize($space);
}
@mixin mr($space) {
margin-right: bsize($space);
}
@mixin p($space) {
padding: bsize($space);
}
@mixin pt($space) {
padding-top: bsize($space);
}
@mixin pb($space) {
padding-bottom: bsize($space);
}
@mixin pl($space) {
padding-left: bsize($space);
}
@mixin pr($space) {
padding-right: bsize($space);
}
@mixin mx($space) {
@include ml($space);
@include mr($space);
}
@mixin my($space) {
@include mt($space);
@include mb($space);
}
@mixin px($space) {
@include pl($space);
@include pr($space);
}
@mixin py($space) {
@include pt($space);
@include pb($space);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment