Search code examples
htmlcssflexbox

Flexbox - Move a certain column from a row to the next row


I am trying to create the following structure:

.rowblock {
 display: flex;
 padding: 0.5rem;
 width: 100%;
 flex-direction: row;
}
.col {
 height: 50px;
 border: 1px solid #ccc;
}
<div class="rowblock">
 <div class="col">10% Width</div>
 <div class="col">80% Width</div>
 <div class="col">100% on Next Row</div>
 <div class="col">10%</div>
</div>

I am trying to move the 3rd column to the next row to occupy the full width. I tried using flex grow but it did not work. Please suggest an approach.


Solution

  • .rowblock {
      display: flex;
      padding: 0.5rem;
      width: 100%;
      flex-wrap: wrap;
    }
    
    .col {
      height: 50px;
      border: 1px solid #ccc;
      flex-grow: 1;
    }
    
    .col:nth-child(1) {
      order: 1;
      flex-basis: calc(10% - 2px);
    }
    
    .col:nth-child(2) {
      order: 2;
      flex-basis: calc(80% - 2px);
    }
    
    .col:nth-child(3) {
      order: 4;
      flex-basis: calc(100% - 2px);
    }
    
    .col:nth-child(4) {
      order: 3;
      flex-basis: calc(10% - 2px);
    }
    <div class="rowblock">
      <div class="col">10% Width</div>
      <div class="col">80% Width</div>
      <div class="col">100% on Next Row</div>
      <div class="col">10%</div>
    </div>

    In the modified code, I added the flex-wrap: wrap; property to the .rowblock class to allow the columns to wrap onto the next line when necessary.

    For the columns, I used the flex-basis property to specify the initial width as a percentage. The first column has a width of 10%, the second column has 80%, the third column has 100% (which forces it onto the next row), and the fourth column has 10%.

    With these modifications, you should achieve the desired structure with the specified column widths.

    UPDATED:

    I've updated the code with the order property as well as subtracting 2px in the flex-basis property to make up for the px's added by the col border.