I’m trying to make all items the same width in flexbox container when they have only max-width
and min-width
defined. It’s flex row with wrapped lines. With setting flex grow to 1 and flex basis to 0 I’m able to achive the same width for all items expect last line if there is extra space left.
I’m wonder if it’s even possible to have all flex items the same width without specified width.
Here is example:
.container {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 200px;
gap: 10px;
background-color: lightseagreen;
}
.item {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
background-color: coral;
padding: 10px;
min-width: 100px;
max-width: 150px;
height: 40px;
}
<div class="container">
<div class="item">some text</div>
<div class="item">some other text but longer</div>
<div class="item">longer</div>
<div class="item">some other</div>
<div class="item">some other text but longer</div>
</div>
I would like to make the last div the same width as others but at the same time I would like to make divs in first and second row fill the space.
3
Answers
I accomplished my goal with
grid
and without fixed width. Grid'sgrid-template-columns
let me do exactly what I wanted. The only caveat of this solution is that the grid ignores themax-width
of its items. It will work only if handlingmax-width
can be moved from children to parent.I'm posting an example with a code that responds to my question but in a specific place in a project that I wanted to implement it works much better without
max-width
and withminmax(100px, 1fr)
.I hope this is what you are referring to.
From my perspective, yes, yes it is possible to have all flexible elements of the same width without a specified width.
In my case the solution is to use the percentage inside the width of the item.
Use the same dimensions that you put of the container. I just calculated that each item takes half the space, using the value of 48%.
If the container had the width in 100%, with that you put in the items the width in 50% already would occupy the half of space each item.
Keep in mind that if you add the gap, it affects the space that each item has.
As an opinion, I would use grid layout to make this type of layout. Among some advantages, it is done in less code.
Unfortunately, it not is possible to make all all items the exact same width when they only have a min-width and max-width defined. The flex-grow property specifies how much the item will grow relative to the rest of the flexible items inside the same container, but because all of the have the same flex-gow value, any remaning space will be distributed equally between them. Instead you should use fixed width with percentage with and css grid. Here is a site to help you with css Grid: https://www.w3schools.com/css/css_grid.asp