Flex justify-content: space-betweenで最後の行を左寄せにする
目的
Flexboxで5カラムの要素を並べたい時、最後の要素が5に満たない時、レイアウトが崩れてしまう。
書き方
html
<ul class="flex">
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
// 空のボックスを用意する
<li class="flex__item--empty"></li>
<li class="flex__item--empty"></li>
<li class="flex__item--empty"></li>
<li class="flex__item--empty"></li>
</ul>
scss
.flex {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
&__item {
width: 18%; /* 横幅を指定する */
&--empty {
width: 18%; /* 空の要素にも同じ横幅を指定する */
}
}
}
追記 justify-content: flex-start; で揃える方法
メリット:不要なHTMLを書かずに済む
サンプルコード:https://codepen.io/Maro1027/pen/abwqvZK
html
<ul class="flex">
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
<li class="flex__item">Sample</li>
</ul>
scss
.flex {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
&__item {
background: orange;
width: calc((100% - 80px) / 5);
height: 140px;
margin-right: 20px;
&:nth-child(5n) {
margin-right: 0px;
}
&:nth-child(n+6) {
margin-top: 20px;
}
}
}
参考サイト
Flexbox で全体を中央に配置しつつ最後の行を左揃えにする
Flexboxのjustify-contentで最後の行を左寄せにする方法
Author And Source
この問題について(Flex justify-content: space-betweenで最後の行を左寄せにする), 我々は、より多くの情報をここで見つけました https://qiita.com/Maro1027/items/682f6470235c40450400著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .