Search code examples
cssflexbox

Create tabular layout with flexbox


Currently, I'm struggling with implementing a table-like layout with flexbox. Unlike other solutions, this one doesn't have 4th header for its column. But each item box fills its col. enter image description here I would appreciate it if you could guide me.

For the header and each item, I used justify-content: space-between;, but the header and items won't match, which is normal. Since items' length vary... I couldn't figure out how to deal with the last col and match it with each item.

[Updated] - A quick demo would be: HTML: enter image description here SCSS: enter image description here


Solution

  • Set the cell or flex-child/s width to 25% as you have 4 columns. Then set the flex-parent to flex-wrap: wrap, this will force the elements in the flex-parent to wrap.

    .cont {
      display: flex;
      flex-wrap: wrap;
    }
    
    .cell {
      width: 25%;
    }
    <div class="cont">
      <div class="heading cell">heading</div>
      <div class="heading cell">heading</div>
      <div class="heading cell">heading</div>
      <div class="heading cell"></div>
      <div class="item cell">Item 1</div>
      <div class="item cell">Item 2</div>
      <div class="item cell">Item 3</div>
      <div class="item cell">Button 1</div>
      <div class="item cell">Item 1</div>
      <div class="item cell">Item 2</div>
      <div class="item cell">Item 3</div>
      <div class="item cell">Button 2</div>
      <div class="item cell">Item 1</div>
      <div class="item cell">Item 2</div>
      <div class="item cell">Item 3</div>
      <div class="item cell">Button 3</div>
    </div>