skip to Main Content

I have a layout that consists of rows that contain columns (they are all divs). I want to create the illusion of a column based table, even though I am using rows.

I want each column in a row to match the corresponding column in another row’s width. So for example, column 2 in row 1 is 300px, therefore column 2 in row 2 is also 300px. But column 1 or 3 could be other widths (but equal to their corresponding column).

The tricky part is that the columns can be different widths depending on content in them, so I can just give them specific widths to start.

enter image description here

Is this possible with CSS grid of flex box? Or does the fact these columns are in separate rows make it impossible without javascript?

EDIT: clarification

2

Answers


  1. CSS Tables can do that.

    .grid {
      display: table;
      table-layout: fixed;
      width: 100%;
    }
    
    .row {
      display: table-row;
    }
    
    .item {
      outline: 1px solid red;
      display: table-cell;
      height: 50px;
    }
    
    .wide {
      width: 300px;
    }
    
    .slim {
      width: 50px;
    }
    <div class="grid">
      <div class="row">
        <div class="item wide"></div>
        <div class="item"></div>
        <div class="item slim"></div>
        <div class="item"></div>
      </div>
      <div class="row">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
      </div>
      <div class="row">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
      </div>
    </div>
    Login or Signup to reply.
  2. With flex-box you can use flex-grow on the child elements using a class or id to specify the particular child element you wish to affect.

    .parent {
      border: 1px solid black;
    }
    
    .data {
      height: 2rem;
      flex: 1;
    }
    
    .row {
      display: flex;
    }
    
    .parent>div:nth-of-type(2){
      border-top: 1px solid black;
    }
    
    .row div {
      align-content: center;
      text-align: center;
    }
    
    .col1 {
      flex-grow: 0.5;
      background-color: #E7E7E7;
    }
    
    .col2 {
      flex-grow: 1;
      background-color: #A9A9A9;
    }
    
    .col3 {
      flex-grow: 0.5;
      background-color: #696969;
    }
    
    .data {
      flex-grow: 2;
      background-color: white;
    }
    <div class="parent">
      <div class="row">
        <div class="data"></div>
        <div class="col1">Col 1</div>
        <div class="col2">Col 2</div>
        <div class="col3">Col 3</div>
      </div>
      <div class="row">
        <div class="data"></div>
        <div class="col1">Col 1</div>
        <div class="col2">Col 2</div>
        <div class="col3">Col 3</div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search