0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[CSS] flex-boxのspace-betweenで最後の行を左寄せしたいとき

Last updated at Posted at 2023-11-24

アイテムボックスのようなものを、こう並べたいと思う。
理想

<div class="parent_element">
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item">box</div>
</div>

一目、こう指定するだけでいいと思う。

.parent_element {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.item {
  width: 30%;
  padding: 1em;
  margin-bottom: 1em;
  background-color: #fff;
  border: 1px solid gray;
  text-align: center;
}

しかし最後の行が中途半端な数の場合、うまくいかない。
現実
なぜなら、space-betweenだから。

解決策1 (非推奨)

HTMLに要素を追加して透明にする。

<div class="parent_element">
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item">box</div>
  <div class="item" style="opacity:0">box</div>
</div>

あまりにやっつけ仕事である。
さらに、レスポンシブで列数が変わる(ブレイクしたとき)毎のstyleを記述しなければならない。

解決策2 (推奨) 擬似要素を使用する

スペーサーとして擬似要素を使用する。

.parent_element {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  &::after {
    content: '';
    display: block;
    width: 30%;
  }
}
.item {
  width: 30%;
  padding: 1em;
  margin-bottom: 1em;
  background-color: #fff;
  border: 1px solid gray;
  text-align: center;
}

レスポンシブにも対応しており、現場で使用していて過不足がない。

解決策3 gapを使用する

現時点ではこれが一番すっきりすると思う。擬似要素は使用しない。

.parent_element {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  gap: 1em;
}

.item {
  width: 30%;
  padding: 1em;
  margin-bottom: 1em;
  background-color: #fff;
  border: 1px solid gray;
  text-align: center;
}

gapは長らく対応ブラウザが揃わないプロパティであったので念のため使用しない、というのが自分の現場の実情だった。
私は今でもグローバルのサイト(古いデバイスのユーザーが多い)ではgapをなるべく使用しない。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?