Search code examples
cssflexbox

Prevent Flex-wrap 3:1 case


I'm sorry I don't know how to write the right question. But here's the problem I want to solve:

If the container have 4 items, and each item has Flex:1 --> then it will position the items through the order: 1 row with 4 items --> 2 rows with 3 items in row 1 and 1 big item in row 2 ---> 2 rows with 2 items ---> and 4 rows.

Is there any way that I can prevent the case '2 rows, with 3 items in row 1 and 1 big item in row 2'? (the second case)

Same case with a container with 6 items, 8 items,... and so on....

Here's the example:

Example

Thank you very much.


Solution

  • The most simple and elegant solution might be to wrap each two items in separate flex-container with no flex-wrap: wrap;:

    .flex-outer {
      display: flex;
      flex-wrap: wrap;
    }
    
    /* no row-wrapping here */
    /* just leave it with default flex-wrap: nowrap */
    .flex-inner {
      display: flex;
    }
    
    /* Just styles for demo */
    .flex-item {
      width: 200px;
      height: 100px;
      background-color: orange;
      color: white;
      font-size: 3rem;
    }
    <div class="flex-outer">
      <div class="flex-inner">
        <div class="flex-item">
          One
        </div>
    
        <div class="flex-item">
          Two
        </div>
      </div>
      
      <div class="flex-inner">
        <div class="flex-item">
          Three
        </div>
    
        <div class="flex-item">
          Four
        </div>
      </div>
    </div>

    If you want items to take all remaining space, set flex: 1; for .flex-item and .flex-inner.