LoginSignup
28
28

More than 5 years have passed since last update.

flex space-between で折り返した要素をcssだけで左並びにする

Last updated at Posted at 2016-12-26

flex space-between で折り返した要素をcssだけで左並びにする

css3 flexbox のjustify-contentを使うと簡単に様子を並べたり、均等に配置することができます。
その中で、「space-between」というプロパティを使えば両端に要素を配置し均等に隙間を開けることができます。

ただこの「space-between」には問題があって折り返し時に要素が両端に配置されるため真ん中が空いてしまうのです。

調べたところ同じように悩んでいる方もおり、参考にさせて頂きました。
ありがとうございます。

「参考記事」
Flexboxのjustify-contentで最後の行を左寄せにする方法
Flexbox で全体を中央に配置しつつ最後の行を左揃えにする

ただ、ここで扱われていたのはjavascriptで要素を末尾に追加し隙間を埋めるという対応でした。
出来れば、css オンリーで出来ないかと考えたのでやってみました。

問題の space-between

html
<ul class="list_container">
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
css
.list_container {
    list-style: none;
    display: flex;
    flex-flow: wrap;
    width: 600px;
    justify-content: space-between;

}
.list_container li {
    border: solid;
    box-sizing: border-box;
    width: 180px;
}

この状態だとこんな感じになります

スクリーンショット 2016-12-26 18.59.58.png

改良版

下記を追加

css
.list_container li:nth-child(3n+2):last-child {
    margin-left: auto;
    margin-right: 35%;
}

スクリーンショット 2016-12-26 19.09.36.png

イメージした通りの形になりましたね
要素を追加しても減らしても、左寄せのまま変化しています

margin-left:35%; という数字は li の幅である親コンテナーの30%と隙間のの空白の幅5%を足した数字です
ここは%じゃなくてもお好みで固定pxに変えて頂いても大丈夫です!

li:nth-child(3n+2):last-child この書き方は下記のサイトを参考にさせて頂きました。
CSSセレクタで最後の要素が奇数だったときを指定する
説明は参考サイトの内容が詳しいのでそちらを御覧ください。

とりあえず、以上になります。

追記

code pen の方にも投稿したので実際に確認したい方はこちらからどうぞ
https://codepen.io/HidetoNagamatsu/pen/mOZOjK

See the Pen flex space-between Left row by Hideto (@HidetoNagamatsu) on CodePen.

28
28
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
28
28