title: How can I have two rows of uneven, centered elements with flexbox?
body: <p>This is the layout I am trying to create:</p>
  
  <p><a href="https://i.stack.imgur.com/Ecagy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ecagy.png" alt="enter image description here"></a></p>
  
  <p>It is a grid of boxes:</p>
  
  <ul>
  <li>The max amount of elements per box must be configurable (4, in this case, but should be able to be different amounts).</li>
  <li>if the last row is not complete and has "orphans", the elements must remain centered, but with the same width as the other boxes.</li>
  <li>The grid must use the whole width of its container. This means, no space surrounding the boxes outside, when the row is full.</li>
  <li><strong>Preferably</strong> must exist a way to set the gap between boxes</li>
  </ul>
  
  <p>I thought the best tool for this would be flexbox but I have encountered the following problems:</p>
  
  <p>My approach was this:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.boxes {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  
  .box {
    width: 22%;
    height: 200px;
    /* pure decoration... */
    box-shadow: 0 0 10px black inset;
    background: green;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="boxes"&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
    &lt;div class="box"&gt;&lt;/div&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>which yields this result:</p>
  
  <p><a href="https://i.stack.imgur.com/v6koi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v6koi.png" alt="enter image description here"></a></p>
  
  <p><a href="https://codepen.io/dbugger/pen/VwLwedr?editors=0100" rel="nofollow noreferrer">Codepen link</a></p>
  
  <p>Here there are several problems:</p>
  
  <ol>
  <li>The last row is not centered.</li>
  <li>I cannot set a fixed margin between boxes. I would like also that this margin is always the same, no matter how many elements a row can fit.</li>
  <li>Minor inconvenience really, but the way to set the amount of max elements per row is flaky. I would have to make an operation dividing 100 / max, which may result in weird results (100 / 3 = 33.333333...).</li>
  </ol>
  
  <p>How could I get a better result?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>A requirement that I forgot to add:</p>
  
  <ul>
  <li>The grid must use the whole width of its container. This means, no space surrounding the boxes outside, when the row is full.</li>
  </ul>