title: Fit boxes dynamically in a container with flexbox
body: <p>I want to arrange boxes dynamically in a container using flexbox. The arrangement looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/VEVMx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VEVMx.png" alt="Display rules"></a></p>
  
  <p>For three or four boxes, the boxes should arrange like in first pic.
  For six boxes, the boxes should fit in two rows with three columns. However for seven boxes, the arrangement should look like that displayed in second picture, and so on.</p>
  
  <p>The width and height of the container are fixed.</p>
  
  <p>Is this possible purely with Flexbox?</p>
  
  <p>HTML: </p>
  
  <pre><code>&lt;div class="container"&gt;
    &lt;div class="box"&gt;AB&lt;/div&gt;
    &lt;div class="box"&gt;CD&lt;/div&gt;
    &lt;div class="box"&gt;EF&lt;/div&gt;
    &lt;div class="box"&gt;GH&lt;/div&gt;
    &lt;div class="box"&gt;IJ&lt;/div&gt;
    &lt;div class="box"&gt;KL&lt;/div&gt;
    &lt;div class="box"&gt;MN&lt;/div&gt;
    &lt;div class="box"&gt;OP&lt;/div&gt;
    &lt;div class="box"&gt;QR&lt;/div&gt;
    &lt;div class="box"&gt;ST&lt;/div&gt;
    &lt;div class="box"&gt;UV&lt;/div&gt;
    &lt;div class="box"&gt;XY&lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>CSS: </p>
  
  <pre><code>.container {
    width: 160px;
    height: 160px;
    border: 1px solid blue;
    display: flex;
  }
  
  .box {
    border: 1px solid red;
    text-align: center;
  }
  </code></pre>
  
  <p>JavaScript:</p>
  
  <pre><code>function align(nodes) {
      var nodeLength = nodes.length;
      if(nodeLength == 1) {
    // nodes occupies entire box
    }
  
    else if (nodeLength == 2) {
      // nodes displayed in two columns
    }
  
    else if(nodeLength &gt; 2 &amp;&amp; nodeLength &lt; 5) {
    // nodes displayed in two rows, two columns
    }
  
    else if(nodeLength &gt; 4 &amp;&amp; nodeLength &lt;= 6) {
    // display in two columns and three rows
    }
  
   /*
     .
     .
     .
     and so on
   */
  }
  
  var boxes = document.getElementsByClassName('box');
  
  align(boxes);
  </code></pre>
  
  <p><a href="https://jsfiddle.net/dk49/ye4Lv48u/1/" rel="nofollow noreferrer">Here</a> is a fiddle for the same.</p>