Back to Blog

SCSSのmixinsの使い方

Web

2024/05/08


$breakpoints: (
    'phone': (320px, 480px),
    'pad': (481px, 768px),
    'tablet': (769px, 1024px),
    'desktop': (1025px, 1200px),
    'large': 1201px
);
@mixin response($breakname) {
    $bp: map-get($breakpoints, $breakname);
    @if type-of($bp) == 'list' {
        @media (min-width: nth($bp, 1)) and (max-width: nth($bp, 2)) {
            @content;
        }
    } @else {
        @media (min-width: $bp) {
            @content;
        }
    }
}

.header {
    width: 100%;
    @include response('phone') {
        height: 50px;
    }
    @include response('pad') {
        height: 60px;
    }
}

生成後のCSSは、下記になります。


.header {
  width: 100%;
}
@media (min-width: 320px) and (max-width: 480px) {
  .header {
    height: 50px;
  }
}
@media (min-width: 481px) and (max-width: 768px) {
  .header {
    height: 60px;
  }
}

Reference
・@mixin and @include
 https://sass-lang.com/documentation/at-rules/mixin/
・Flow control(@if and @else)
 https://sass-lang.com/documentation/at-rules/control/if/
・変数>Maps
 https://sass-lang.com/documentation/values/maps/
・変数>Lists
 https://sass-lang.com/documentation/values/lists/

Related Posts