[SCSS] SCSS Spacing(margin&padding) 믹스인

부트스트랩을 사용할때 m-3, px-2 같은 클래스를 써서 마진또는 패딩을 준다.

html 에서 말고 scss 에서 믹스인 형식으로 @include m(3); 요렇게 쓰고 싶을 때 아래 scss 파일을 적당히 임포트 시켜서 쓰면된다.

_mixins.scss

$spacer: 1rem !default;
$spacers: () !default;
// stylelint-disable-next-line scss/dollar-variable-default
$spacers: map-merge(
    (
        0: 0,
        1: (
            $spacer * 0.25
        ),
        2: (
            $spacer * 0.5
        ),
        3: $spacer,
        4: (
            $spacer * 1.5
        ),
        5: (
            $spacer * 3
        )
    ),
    $spacers
);

@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);
}

.test {
    @include my(1);
}

사용

마이너스

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

패딩 & 마진주기

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

값지정

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

Auto

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