Steffi
Steffi

Reputation: 7057

How to get same column width using Flexbox?

Is there a way to get same column width on different rows using Flexbox ?

I would like to have the same width for cell--id (The width must have the width of the largest cell--id).

Example:

<div class="container">
  <div class="row">
    <div class="cell cell--id">1</div>
    <div class="cell">Test</div>
  </div>
  <div class="row">
    <div class="cell cell--id">2222</div>
    <div class="cell">Test</div>
  </div>
</div>

CSS :

<style>
   .row { display: flex }
</style>

Upvotes: 13

Views: 20669

Answers (2)

Rene van der Lende
Rene van der Lende

Reputation: 5281

Your need to think:

  • in rows of one or more columns => row is the flexible container
  • or in columns of one or more rows => column is the flexible container
  • the contents are flexed items (and can be nested flexible containers)

In your case you need to give .row a width and make flexbox split the cells evenly over the row:

.row  { display: flex; width: 300px }
.cell { flex: 1 } /* each cell width will be: available space divided by the number of cells */

Ok, here's the POC:

        .row    { display: flex; width: 500px }
        .cell   { flex: 1 }
<div class="container">
  <div class="row">
    <div class="cell cell--id">1</div>
    <div class="cell">Test</div>
  </div>
  <div class="row">
    <div class="cell cell--id">2222</div>
    <div class="cell">Test</div>
  </div>
  <div class="row">
    <div class="cell cell--id">2222222222222</div>
    <div class="cell">Test</div>
  </div>
</div>

Upvotes: 6

CupawnTae
CupawnTae

Reputation: 14580

You're basically describing a table, so you should probably be using table layout instead, e.g.

.row { display: table-row }
.cell { display: table-cell }
<div class="container">
  <div class="row">
    <div class="cell cell--id">1</div>
    <div class="cell">Test</div>
  </div>
  <div class="row">
    <div class="cell cell--id">2222</div>
    <div class="cell">Test</div>
  </div>
</div>

If you're dead set on flexbox, I see two options:

  1. if your rows are going to be the same height, you could swap to column-major - i.e. put your column divs outside your row divs
  2. manually manage the size of the columns, similar to this: http://inlehmansterms.net/2014/10/11/responsive-tables-with-flexbox/

But really, I think you want table layout.

Upvotes: 8

Related Questions