Search code examples
cssflexboxgrid-layoutcss-grid

Evenly sized columns between rows using grid/flex


Consider the following snippet:

#container{
  border: solid 1px black;
  display: inline-grid;
  grid-template-columns: repeat(3, auto);
}
<div id="container">
  <div class="row">
    <div class="item">A1111</div>
    <div class="item">B1</div>
    <div class="item">C1</div>
  </div>
  <div class="row">
    <div class="item">A2</div>
    <div class="item">B2222</div>
    <div class="item">C2</div>
  </div>
  <div class="row">
    <div class="item">A3</div>
    <div class="item">B3</div>
    <div class="item">C3333</div>
  </div>  
</div>

The end result is a table-like display where each item of every row is the width of the widest item in that column.

A1111 A2    A3
B1    B2222 B3
C1    C2    C3333

Which is great - but I need the table laid out as rows...

A1111 B1    C1
A2    B2222 C2
A3    B3    C3333

display: table solves this - but table has some drawbacks around spacing, alignments and so-on. Therefore, grid and flex looks attractive.

Alas I cannot figure out how to get the information laid out as desired.

Adding display: grid to .row helps the order of information, but doesn't retain the equal column widths.

The item content will vary, and so cannot use fixed widths and it is not desired that the grid/flex spans the entire page/containing width.


Solution

  • You can define which column the grid item should be using grid-column. This means the row doesn't require a containing row div.

    Working example...

    #container{
      border: solid 1px black;
      display: inline-grid;
      grid-auto-flow: row;
      grid-gap: 10px;
      padding: 10px;
    }
    
    .col1{
      grid-column: 1;
    }
    
    .col2{
      grid-column: 2;
    }
    
    .col3{
      grid-column: 3;
    }
    <div id="container">
        <div class="col1">A11111</div>
        <div class="col2">B1</div>
        <div class="col3">C1</div>
        <div class="col1">A2</div>
        <div class="col2">B2222222</div>
        <div class="col3">C2</div>
        <div class="col1">A3</div>
        <div class="col2">B3</div>
        <div class="col3">C33333333</div>
      </div>
    </div>