Search code examples
htmlcssflexboxcss-grid

Is there a way to dynamicly take out HTML elements from a grid or flexbox?


Is there a way that if I have a grid like this:

.grid {
  display: flex;
  justify-content: start;
}
<div class="grid">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>

By applying a .right class some elements are taken out of the order and placed at the end of the grid and justified to the right (end).

I'm trying to achieve something like this:

enter image description here

The hardship comes from not knowing ahead of time how many .left and .right items there will be...


Solution

  • Flexbox can do that with order and margin on the appropriate elements.

    We can also leverage :nth-child(n of x) to select the first classed element to which to apply the margin.

    Support

    .flexy {
      display: flex;
      margin-top: 25px;
    }
    
    .item {
      border: 1px solid grey;
      padding: 0.25em;
    }
    
    :nth-child(1 of .right) {
      margin-left: auto;
    }
    
    .right {
      order: 2;
    }
    <div class="flexy">
      <div class="item">Item 1</div>
      <div class="item right">Item 2</div>
      <div class="item">Item 3</div>
      <div class="item right">Item 4</div>
    </div>
    
    <div class="flexy">
      <div class="item">Item 1</div>
      <div class="item right">Item 2</div>
      <div class="item">Item 3</div>
      <div class="item right">Item 4</div>
      <div class="item">Item 5</div>
      <div class="item right">Item 6</div>
    </div>