対象コード

CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<style> body{ padding: 0 100px; } .container{ display: flex; flex-flow: row wrap; justify-content: center; padding-inline-start: 0; } .box{ height: 100px; width: 100px; background: #333; margin: 10px; list-style: none; } .box.empty-box { height: 0; padding-top: 0; padding-bottom: 0; margin-top: 0; margin-bottom: 0; } </style> |
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<body> <ul class="container"> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> <li class="box"></li> </ul> </body> |
JavaScript
1 2 3 4 5 6 7 8 9 10 |
<script> var container = $('.container'), emptyBoxs = [], i; // 子要素の数だけ空の子要素を追加。 for (i = 0; i < container.find('.box').length; i++) { emptyBoxs.push($('<li>', { class: 'box empty-box' })); } container.append(emptyBoxs); </script> |
動作確認

何をしているのかというと、高さや余白が 0 の空の子要素を実際の子要素数だけ追加しています。
そのようにすることで、親要素の幅に依存せず中央左寄せに表示されるわけですね。
今回はJavaScriptを使用しての実装となりましたが、願わくばCSSのみで実装したいところです。