I'm trying to create a grid with maximum 3 columns. However, if there are only 2 items in the grid, I want them to stretch to occupy 50% of the space each.
At the moment, this much is working, but if the amount of items in the grid isn't a multiple of 3, the remaining items stretch to occupy the rest of the space. I want them to all have an equal width. Is this possible?
This is how far I've got:
https://codepen.io/elly175/pen/jOqJNXa
.flex-container {
display: flex;
flex-wrap: wrap;
margin: 40px 0;
width: 900px;
box-sizing: border-box;
}
.flex-item {
box-sizing: border-box;
padding: 15px 18px;
font-size: 16px;
border: 1px solid #777;
flex: 1;
min-width: 33.33%;
}
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
</div>
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
<div class="flex-item">Three</div>
<div class="flex-item">Four</div>
<div class="flex-item">Five</div>
<div class="flex-item">Six</div>
<div class="flex-item">Seven</div>
</div>
You can disable the flex-grow
if the element is not the first or the second:
.flex-container {
display: flex;
flex-wrap: wrap;
margin: 40px 0;
box-sizing: border-box;
}
.flex-item {
box-sizing: border-box;
padding: 15px 18px;
font-size: 16px;
border: 1px solid #777;
flex: 1;
min-width: 33.33%;
}
.flex-item:not(:first-child):not(:nth-child(2)) {
flex-grow:0;
}
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
</div>
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
<div class="flex-item">Three</div>
</div>
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
<div class="flex-item">Three</div>
<div class="flex-item">Four</div>
<div class="flex-item">Five</div>
</div>
<div class="flex-container">
<div class="flex-item">One</div>
<div class="flex-item">Two</div>
<div class="flex-item">Three</div>
<div class="flex-item">Four</div>
<div class="flex-item">Five</div>
<div class="flex-item">Six</div>
<div class="flex-item">Seven</div>
</div>
you can add flex-basis:33.33% or in this case width:33.33% to the items, not min-width. of course, you can add flex:0 0 33.33%. which means flex-grow and shrink 0. so the width won't change on different containers. maybe this helps:
.flex-item {
box-sizing: border-box;
padding: 15px 18px;
font-size: 16px;
border: 1px solid #777;
flex: 0 0 33.33%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With