blankface
blankface

Reputation: 6347

Move last item in flexbox to new line when items take up different width

.main{
  display:flex;
  border: 1px solid black;
}

.item, .item2, .item3, .item4{
  padding: 10px;
}

.item {
  flex-grow: 1;
  flex-wrap: wrap;
}

.item2{
  flex-grow: 7;
  background-color: pink;
}

.item3 {
  flex-grow: 2;
  background-color: yellow;
}
<div class="main">
  <div class="item">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
</div>

In the above scenario, how can I move item 4 into a new line? All the examples I've seen, it's possible when the items are of the same width.

Upvotes: 2

Views: 1368

Answers (2)

Temani Afif
Temani Afif

Reputation: 272807

You need to activate the wrap on the parent element (the flex container) then make the element full width:

.main{
  display:flex;
  border: 1px solid black;
  flex-wrap:wrap;
}

.item, .item2, .item3, .item4{
  padding: 10px;
}

.item {
  flex-grow: 1;
}

.item2{
  flex-grow: 7;
  background-color: pink;
}

.item3 {
  flex-grow: 2;
  background-color: yellow;
}
.item4 {
  flex-basis:100%;
}
<div class="main">
  <div class="item">1</div>
  <div class="item2">2</div>
  <div class="item3">3</div>
  <div class="item4">4</div>
</div>

Upvotes: 2

pretzelhammer
pretzelhammer

Reputation: 15105

Use .item-groups to organize your .items by row. Example:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.main {
  display: flex;
  border: 1px solid black;
  flex-wrap: wrap;
}

.item-group {
  flex-basis: 100%;
  display: flex;
}

.item1, .item2, .item3, .item4 {
  padding: 10px;
}

.item1 {
  flex-grow: 1;
}

.item2{
  flex-grow: 7;
  background-color: pink;
}

.item3 {
  flex-grow: 2;
  background-color: yellow;
}

.item4 {
  background-color: violet;
}
<div class="main">
  <div class="item-group">
    <div class="item1">1</div>
    <div class="item2">2</div>
    <div class="item3">3</div>
  </div>
   <div class="item-group">
    <div class="item4">4</div>
  </div>
</div>

Upvotes: 1

Related Questions