Simple Bootstrap SASS Spacing Utility

css, sass, web

I find myself often working with different CSS/SASS frameworks and always reaching for spacing utility classes like Bootstrap. To me it is pretty straight forward to understand if an element or component has padding or margin applied that will override its default styles just by looking at markup.

So I tend to write this very often and include it in other frameworks:

$spacer: .25rem;

$positions: (
    t: 'top',
    r: 'right',
    l: 'left',
    b: 'bottom',
);

@for $i from 1 through 5 {
    .m-#{$i} {
        margin: $spacer * $i;
    }

    .p-#{$i} {
        padding: $spacer * $i;
    }

    .m-x-#{$i} {
        margin-top: $spacer * $i;
        margin-bottom: $spacer * $i;
    }

    .p-y-#{$i} {
        padding-top: $spacer * $i;
        padding-bottom: $spacer * $i;
    }

    @each $k,$v in $positions {
        .m-#{$k}-#{$i} {
            margin-#{$v}: $spacer * $i;
        }
    
        .p-#{$k}-#{$i} {
            padding-#{$v}: $spacer * $i;
        }
    }
}