4
3

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 5 years have passed since last update.

flex space-between で折り返した要素の左寄せがつらい

Last updated at Posted at 2019-08-25

とりあえずの結論

折り返しする場合は、space-betweenを使わず子要素のpaddingで調整すると便利かもしれない
※デメリットはdivが増えてしまうこと

See the Pen space-between 3 by eights-net (@eights_net) on CodePen.

space-between

要素を均等に並べるときにとても便利

See the Pen space-between by eights-net (@eights_net) on CodePen.

space-between 折り返しの問題

複数行になったとき flex-wrap: wrap を使って折り返しをした場合、
要素数によって左寄せにならない問題

See the Pen space-between 2 by eights-net (@eights_net) on CodePen.

解決策参考

カラム数によって疑似要素や空divを置いたりjsで追加したりして調整していたが、
CMSなどで要素の数が変わったり、「カラム数を3から4に変更で」なんて言われたりするととてもつらい

そこで別解決法

そもそも space-between を使わず子要素の余白で均等にしようという本末転倒?の解決法

子要素に直接 margin をつけてもいいが width を調整しないといけないので、
子要素を囲う div を作り、その囲いの左右padding と width を設定することで均等にしよう作戦

See the Pen space-between 3 by eights-net (@eights_net) on CodePen.

解説

  • 子要素(.item) を囲う div(.item-wrap) を用意し、その div の padding で余白を取り、width をつける
    • 通常の flexbox だけで作るより div が増えてしまう点はデメリット
    • 子要素に背景色を付けたい場合は .item-wrap ではなく .item に付ける
  • div(.item-wrap) の width は3カラムの場合 calc(100% / 3) で指定する。4カラムの場合は calc(100% / 4)
    • 100%をカラムで割るだけなのでカラム数が変更になった場合も修正が簡単
  • div(.item-wrap) の padding は余白を取りたい幅の半分を左右に付ける
    • 30pxの余白が欲しい場合は padding: 0 15px;
  • 親要素(.container) に子要素の padding と同じ値を -margin をつけて子要素のはみ出しを打ち消す
    • 余白が30pxの場合は margin: 0 -15px;
    • -margin を付けても子要素の幅は飛び出したままなので取り扱い注意
    • その場合は overflow: hidden; するといいかもしれない
  • 親要素(.container)には幅を指定せず、指定したい場合はさらに親(.container-wrap)で指定する
    • 親要素に直接指定すると崩れてしまうのでその場合も div が増えてしまうデメリットがある

結論

divは増えてしまいますが変更には強いのでオススメです
基本的には Bootstrap の flex grid を参考にしています
ミスなどあればご指摘お願いいたします

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?