Search code examples
cssflexboxvertical-alignment

Float to right, left and top grid


I have that HTML:

<div class="row">
  <div class="cell left">A</div>
  <div class="cell left">B</div>
  <div class="cell right">C</div>
  <div class="cell left">D</div>
  <div class="cell right">E</div>
  <div class="cell left">F</div>
</div>

I want to obtain that:

Example:

All "cell left" have to be align to left and top. All "cell right" have to be align to right and top.

The layout of the HTML must remain as is. How to define CSS using FLEX or FLOAT? The order or number of cells in each row is not known or regular.

I tried to do it using FLEX or FLOAT, but the right cells are not top-aligned.


Solution

  • A simple solution would be using display: grid.

    More about grid layout

    When in display: grid, the placing of items can be specified such as:

    /* In 2 columns of same size, auto place item by row and fill gaps */
    
    grid-template-columns: repeat(2, 1fr);
    grid-auto-flow: row dense;
    

    Then, left and right classes can specify which grid-column the div should be placed.

    Here is a quick example:

    .row {
      display: grid;
      width: 500px;
      grid-template-columns: repeat(2, 1fr);
      grid-auto-flow: row dense;
      gap: 12px;
      outline: 2px solid #000;
      padding: 12px;
    }
    
    .cell {
      padding: 12px;
    }
    
    .left {
      grid-column: 1 / span 1;
      background-color: pink;
    }
    
    .right {
      grid-column: 2 / span 1;
      background-color: lightgreen;
    }
    <div class="row">
      <div class="cell left">A</div>
      <div class="cell left">B</div>
      <div class="cell right">C</div>
      <div class="cell left">D</div>
      <div class="cell right">E</div>
      <div class="cell left">F</div>
    </div>