Reputation: 12598
I have a basic flexbox implementation that handle 3 columns, if 2 or 1 columns are used then it automatically fills the space to handle it..
.grid3 {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.grid3-item {
flex-basis: 33.333%;
text-align: center;
flex:1;
background:grey;
}
<div class="grid3">
<div class="grid3-item">
Some Content
</div>
<div class="grid3-item">
Some Content
</div>
<div class="grid3-item">
Some Content
</div>
</div>
I am trying to make it so that if there are more than 3 columns then they will be handled on a new row, so for example 5 columns would looks like this
Is it possible to achieve this using flexbox? The items are generated dynamically so I want to be able to handle any number of potential items.
Upvotes: 2
Views: 4379
Reputation: 371231
.grid3 {
display: flex;
flex-wrap: wrap;
}
.grid3-item {
flex: 1 0 26%;
text-align: center;
background: lightgrey;
}
<div class="grid3">
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
</div>
The flex: 1 0 26%
shorthand rule breaks down to this:
flex-grow: 1
flex-shrink: 0
flex-basis: 26%
With flex-grow: 1
there's no need for flex-basis
to be 33.333%.
Since flex-grow
will consume free space on the row, flex-basis
only needs to be large enough to enforce a wrap.
In this case, with flex-basis: 26%
and flex-shrink: 0
, a maximum of three items can exist on the line. (Plus, there's plenty of room for margins, if you want them.)
Upvotes: 1
Reputation: 60563
you can use flex-basis
along with flex-grow: 1
for that:
.grid3 {
display: flex;
flex-wrap: wrap;
}
.grid3-item {
flex: 1 0 33%;
text-align: center;
border: 1px solid red;
box-sizing: border-box
}
<div class="grid3">
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
<div class="grid3-item">Some Content</div>
</div>
Upvotes: 2
Reputation: 443
Yep, this is exactly what flexbox is for. You just needed a "min-width".
This works for any number of boxes that I try.
.grid3 {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.grid3-item {
flex-basis: 33.333%;
min-width: 33.3%;
text-align: center;
flex:1;
background:grey;
}
<div class="grid3">
<div class="grid3-item">
Some Content
</div>
<div class="grid3-item">
Some Content
</div>
<div class="grid3-item">
Some Content
</div>
<div class="grid3-item">
Some Content
</div>
<div class="grid3-item">
Some Content
</div>
</div>
Upvotes: 0