LoginSignup
9
12

More than 5 years have passed since last update.

メディアクエリ用 Mixin

Last updated at Posted at 2015-11-17

目的

Sass でメディアクエリをいちいち書くと長くなるし DRY でなくなるので、
Mixin にして簡潔に書けるようにする。

実装

_respond-to.scss
// Breakpoints
$large-screen: 1200px;
$medium-screen: 992px;
$small-screen: 768px;

@mixin respond-to($media-list...) {
  @if index($media-list, large) {
    @media screen and (min-width: $large-screen) {
      @content;
    }
  }
  @if index($media-list, medium) {
    @media screen and (min-width: $medium-screen) and (max-width: $large-screen - 1) {
      @content;
    }
  }
  @if index($media-list, small) {
    @media screen and (min-width: $small-screen) and (max-width: $medium-screen - 1) {
      @content;
    }
  }
  @if index($media-list, extra-small) {
    @media screen and (max-width: $small-screen - 1) {
      @content;
    }
  }
}

使用例

main.scss
@import 'respond-to';

main {
  section {
    max-width: 600px;

    @include respond-to(medium) {
      max-width: 400px;
    }

    @include respond-to(extra-small, small) {
      max-width: 200px;
    }
  }
}

CSS はこのようになります。

main.css
main section {
  max-width: 600px;
}
@media screen and (min-width: 992px) and (max-width: 1199px) {
  main section {
    max-width: 400px;
  }
}
@media screen and (max-width: 767px) {
  main section {
    max-width: 200px;
  }
}
@media screen and (min-width: 768px) and (max-width: 991px) {
  main section {
    max-width: 200px;
  }
}

参考

記事

公式ドキュメント

9
12
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
9
12