LoginSignup
5
0

More than 3 years have passed since last update.

Sass(CSS) 等間隔に配置したい

Last updated at Posted at 2020-09-07

前提

SassのSCSS記法を用いる。

index.html
<div class="wrap">
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
</div>
style.scss
.wrap {
  display: flex;
  flex-wrap: wrap;
  width: 30%;
  background: skyblue;

  .circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: blue;
  }
}

スクリーンショット 2020-09-06 14.42.20.png

水色の範囲は画面幅に合わせて30%としているので、可変である。
ここで実現したいことは、

  • 青丸が等間隔に並ぶ
  • 水色の四角の左右に青丸との間隔が無いようにする
  • 下の段の青丸は上の段の間隔に合わせて左詰めにする
  • 画面幅を変えても、上の条件を満たすようにする

試行錯誤① justify-contentでなんとかしたかった

style.scss
.wrap {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 30%;
  background: skyblue;

  .circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: blue;
  }
}

justify-content: space-between; を追加。

スクリーンショット 2020-09-06 14.45.06.png

◎条件を満たしている項目

  • 青丸が等間隔に並ぶ
  • 水色の四角の左右に青丸との間隔が無いようにする

×満たしていない項目

  • 下の段の青丸は上の段の間隔に合わせて左詰めにする

↑を満たすには、justify-contentでは無理そう。

試行錯誤② メディアクエリで頑張る

メディアクエリで青丸の幅を画面サイズに合わせて変える。

style.scss
.wrap {
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-between;
  width: 30%;
  background: skyblue;

  .circle {
    width: calc(100% / 3);
    height: 80px;
    border-radius: 50%;
    background: blue;

    @media screen and (max-width: 900px) and (min-width: 701px){
      width: calc(100% / 4);
    }

    @media screen and (max-width: 1100px) and (min-width: 901px){
      width: calc(100% / 5);
    }

    @media screen and (max-width: 1300px) and (min-width: 1101px){
      width: calc(100% / 6);
    }

    @media screen and (max-width: 1500px) and (min-width: 1301px){
      width: calc(100% / 7);
    }
  }
}

video9_6.gif

画面幅を変更しても、条件を満たす配置になった!

画面幅1500pxまでしか書いていないので、もっと増やしたい...
でも、いちいち書くの面倒なので↓

Sassでfor文を書く

style.scss
    @media screen and (max-width: 900px) and (min-width: 701px){
      width: calc(100% / 4);
    }

    @media screen and (max-width: 1100px) and (min-width: 901px){
      width: calc(100% / 5);
    }

    @media screen and (max-width: 1300px) and (min-width: 1101px){
      width: calc(100% / 6);
    }

    @media screen and (max-width: 1500px) and (min-width: 1301px){
      width: calc(100% / 7);
    }

上で地道に書いたこのコードをSassのfor文を使って書いてみる。

次回に続く。https://qiita.com/mei0210/items/ed468882579a6d3d902e

5
0
1

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
5
0