Reputation: 411
I have children elements in the flexbox. I want them to be responsive and with a max-width of 200px. They scale nicely but since the last row has fewer children than the other rows, the problem is that those are not the same size as the rest, and obviously I want the same dimension for all children.
First, I tried to use grid, but then I am not able to center the children in the last row. So that's not the solution.
I also read a similar question where the answers are that it's just not possible to do with flexbox.
So, how to do it with JavaScript since it's the last option?
.wrapper {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.item {
height: 50px;
flex: 30%;
max-width: 200px;
background: #ababab;
border: 2px solid #000;
}
<div class="wrapper">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Upvotes: 0
Views: 75
Reputation: 20441
Is this what you are looking for?
.wrapper {
display: flex;
flex-wrap: wrap;
box-sizing : border-box;
}
.item {
height: 50px;
width:30%;
max-width: 200px;
background: #ababab;
border: 2px solid #000;
}
<div class="wrapper">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Removing the flex:30%
which is a shorthand for a few properties one of which is flex-grow
. flex-grow lets the children items grow if needed.
Instead of justify-content: center;
I have used the default value flex-start
; so they start from left. You can use justify-content:center
too if that looks better to you.
Upvotes: 2
Reputation: 102
Determine the size of a flex item in a full row. (size S
)
If the last row has a different number of items than a full row does, calculate the number of items there. (count N
)
Update/override the styles for the N
number of flex items from the last so that they have size S
.
You would also want to listen for resize events to reset styles on the N
items and repeat the styling update on a new number of items as needed.
Upvotes: 0