Oteto Blogのロゴ

【SCSS】メディアクエリをmixinと変数でまとめて管理する

やりたいこと

.hoge {
  @media screen and (min-width: 769px) {
    ...
  }
  @media screen and (max-width: 768px) {
    ...
  }
}
  • このようにセレクターごとに毎回メディアクエリをネストして書くのが非効率なので、mixinとして定義して使い回したい
  • ブレイクポイントを変数で管理したい

解決法

mixin

$breakpoint: 768px;
$breakpoint-map: (
  pc: "screen and (min-width: #{$breakpoint + 1px})",
  sp: "screen and (max-width: #{$breakpoint})",
);

@mixin mq($device) {
  @media #{map-get($breakpoint-map, $device)} {
    @content;
  }
}

sass:mapを使ってデバイスとメディアクエリを管理する。もしブレイクポイントを増やしたい場合はmapを拡張してあげればOK。

加えて@contentでコンテンツブロックを渡すことで、mixinで囲んだスタイルを指定したデバイスのみで適用させる。

使用例

@use "xxx" as mixin;

.hoge {
  @include mixin.mq(pc) {
    background-color: red;
  }

  @include mixin.mq(sp) {
    background-color: blue;
  }
}

コンパイル結果

@media screen and (min-width: 769px) {
  .hoge {
    background-color: red;
  }
}
@media screen and (max-width: 768px) {
  .hoge {
    background-color: blue;
  }
}