Search code examples
htmlcssresponsivecss-grid

How can I reverse the CSS grid columns order?


I want to be able to reverse the order of columns (the two small ones to the left, and the big one to the right). I've tried several solutions, but I didn't find one that works.

Enter image description here

Here's the code:

.images-block-box{

    display: grid;
    grid-gap: 16px;
    grid-template-columns: 708fr 340fr;

    & > div:first-child{
      grid-row: span 2;
    }

    &.reverse{
      grid-template-columns: 340fr 708fr;

      & > div:first-child{
         order: 2; // This doesn't work (I want to place the first item at the end of the 3)
      }
    } // reverse

} // images-block-box

Note that I really want to reverse the order of the columns themselves, not just their dimensions.


Solution

  • Simply adjust grid-column and consider grid-auto-flow:dense; to allow the next elements to be placed before:

    .grid {
      display: grid;
      grid-gap: 16px;
      grid-template-columns: 2fr 1fr;
      grid-auto-flow:dense;
      margin:5px;
    }
    
    .grid div {
      min-height: 50px;
      border: 1px solid;
    }
    
    .grid div:first-child {
      grid-row: span 2;
    }
    
    .grid.reverse {
      grid-template-columns: 1fr 2fr;
    }
    
    .grid.reverse div:first-child {
      grid-column:2;
    }
    <div class="grid">
      <div></div>
      <div></div>
      <div></div>
    </div>
    
    <div class="grid reverse">
      <div></div>
      <div></div>
      <div></div>
    </div>

    dense

    If specified, the auto-placement algorithm uses a “dense” packing algorithm, which attempts to fill in holes earlier in the grid if smaller items come up later. This may cause items to appear out-of-order, when doing so would fill in holes left by larger items.ref