LoginSignup
0
0

More than 3 years have passed since last update.

初心者が見落としてしまったメディアクエリの書き順

Posted at

こんにちは。今回はSASSでメディアクエリを使い始めた頃に詰まってしまった所をお伝えしたいと思います。

index.html
...(省略)
  <body>
    <h1>hogehoge</h1>
  </body>
...(省略)

このhtmlに対して、以下のように設定するとmdサイズのときの設定(color:blue)が反映されません。何故でしょうか?

style.scss
$breakpoints: (
  "sm": "screen and (min-width: 375px)",
  "md": "screen and (min-width: 425px)"
) !default;
@mixin mq($breakpoint: md) {
  @media #{map-get($breakpoints, $breakpoint)} {
    @content;
  }
}

h1 {
  color: blue;
  @include mq(md) {
    // 「425px以上はcolor: red」
    color: red;
  }
  @include mq(sm) {
    // 「375px以上はcolor: green」
    color: green;
  }
}

そう、@include mq(md)の後に@include mq(sm)を設定しているからです。超基本なことですが、(詳細度が同じだったら)CSSのルールは後に書いた方が反映されます。なので、@include mq(md)@include mq(sm)の順番を入れ替えましょう。そうするとちゃんと意図した通りに反映されます。

style.scss
$breakpoints: (
  "sm": "screen and (min-width: 375px)",
  "md": "screen and (min-width: 425px)"
) !default;
@mixin mq($breakpoint: md) {
  @media #{map-get($breakpoints, $breakpoint)} {
    @content;
  }
}

h1 {
  color: blue;
  @include mq(sm) {
    // 「375px以上はcolor: green」
    color: green;
  }
  @include mq(md) {
    // 「425px以上はcolor: red」
    color: red;
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0