title: Layout depending on number of elements
body: <p>I have a wrapper that can contain 2, 3 or 4 elements (I don't know it in advance because every element renders itself, depending on API response).</p>
  
  <p>If there are 3 (or less) I want them to stack like:</p>
  
  <p><a href="https://i.stack.imgur.com/34jDk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/34jDk.png" alt="3 elements layout"></a></p>
  
  <p>No big deal. But when there are 4 of them, I need this other layout:</p>
  
  <p><a href="https://i.stack.imgur.com/VP3We.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VP3We.png" alt="4 elements layout"></a></p>
  
  <p>So far, I thought CSS Grid would be the way to go and I tried:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>/* Just to add some interaction to the demo */
  
  const w = document.getElementById("wrapper");
  let x;
  
  function toggle(event) {
  
    const d = document.getElementById("D");
    return d 
      ? 
        x = d.cloneNode() &amp;&amp; w.removeChild(d) 
      : w.appendChild(x);
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
    width: 100%;
    max-width: 500px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 10px;
  }
  
  
  
  .item {
    grid-column-start: span 2
  }
  
  .item:nth-last-child(1),
  .item:nth-last-child(2) {
    grid-column-start: auto;
  }
  
  
  /* Non-relevant CSS here: */
  
  button {
    margin: 20px auto;
    font-size: 16px;
    padding: 3px 6px;
    border-radius: 6px;
  }
  
  #A { background: #7984f7 }
  #B { background: #cb8af8 }
  #C { background: #8cd4fb }
  #D { background: #97f8d8 }
  
  .item {
    border-radius: 6px;
    padding: 10px 0;
    font-family: sans-serif;
    font-weight: bold;
    color: white;
    text-align: center;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper"&gt;
    &lt;div id="A" class="item"&gt;A&lt;/div&gt;
    &lt;div id="B" class="item"&gt;B&lt;/div&gt;
    &lt;div id="C" class="item"&gt;C&lt;/div&gt;
    &lt;div id="D" class="item"&gt;D&lt;/div&gt;
  &lt;/div&gt;
  
  &lt;button onclick="toggle()"&gt;Click me!&lt;/button&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>But it doesn't work for 3 elements... In fact, I've tried many things (all CSS Grid related) and there's probably an easier solution I can't see right now... Any help will be much appreciated!</p>