Search code examples
htmlcssflexbox

How to break line in a flex layout?


I have my first, second, and third items and then I want the forth item to go to the next line no matter how wide is the space.

.box {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  align-items: flex-start;
}
.it {
  max-width: 420px;
}
<div class="box">
  <div class="it">1</div>
  <div class="it">2</div>
  <div class="it">3</div>
  <div class="it">4</div>
</div>


Solution

  • You can insert a wide pseudo-element at the right position:

    .flex-container {
      display: flex;
      flex-wrap: wrap;
    }
    .flex-container::after {
      content: '';
      width: 100%;
    }
    .flex-item:last-child { /* or `:nth-child(n + 4)` */
      order: 1;
    }
    <div class="flex-container">
      <div class="flex-item">1</div>
      <div class="flex-item">2</div>
      <div class="flex-item">3</div>
      <div class="flex-item">4</div>
    </div>