Sass | ブレイクポイント

サンプル

http://xs437226.xsrv.jp/sample/sass-responsive/


ブレイクポイントが2つあって、コンテンツが1段 → 2段 → 4段と変化していきます。

Mac Book (横幅1,440px)

f:id:khirok:20200418202735p:plain

iPad (横幅768px)

f:id:khirok:20200418203101p:plain

iPhone7 (横幅375px)

f:id:khirok:20200418203209p:plain

ソースコード

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="reset.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="box">
    <div class="box__ice-green"></div>
    <div class="box__nile-blue"></div>
    <div class="box__teal-green"></div>
    <div class="box__chrome-green"></div>
  </div>
</body>
</html>

style.scss

scssファイルは、Visual Studio Code拡張機能 Live Sass Compilerを使用して、CSSファイルに変換しました。

@import '_mixin.scss';
.box {
  width: 100vw;
  height: 100vh;
  background-color: #e6eae6;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  &__ice-green {
    background-color: #a3d6cc;
    @include box;
  }
  &__nile-blue {
    background-color: #2cb4ad;
    @include box;
  }
  &__teal-green {
    background-color: #006a6c;
    @include box;
  }
  &__chrome-green {
    background-color: #00533f;
    @include box;
  }
}

_mixin.scss

このファイルは、関数を定義するために作ったファイルです。
style.scssで読み込みました。

@mixin break-point-01 {
  @media (max-width: 1271px) {
    @content;
  }
}
@mixin break-point-02 {
  @media (max-width: 635px) {
    @content;
  }
}
@mixin box {
  height: 30%;
  width: 20%;
  min-width: 288px;
  margin: 15px;
  border-radius: 10px;
  @include break-point-01 {
    width: 35%;
  }
  @include break-point-02 {
    height: 20%;
    max-width: 288px;
  }
}

SASSでブレイクポイントを設定する方法

定義する時

@mixin 変数名 {
  @media (max-width: 〇〇px) {
    @content;
  }
}
@mixin break-point-01 {
  @media (max-width: 1271px) {
    @content;
  }
}

呼び出す時

@include 変数名 {
 プロパティ: 値;
}
@include break-point-01 {
   width: 35%;
}

width: 35%; は、画面幅1271pxまでに適応されます。


例えば、width: 20%; とすでに決まっていて、
画面幅1271pxまでは width: 35%; にしたいという時は、以下のようにすればいいでしょう。

@mixin box {
  width: 20%;
  @include break-point-01 {
    width: 35%;
  }
}

この例では、また@mixinが出てきてややこしいですが、
box-1というクラス名の要素に対して用いる時は

.box-1 {
  @include box;
}

このようにして、@mixinで定義した box という関数を呼び出します。