Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox grid with maximum 3 columns and minimum 2? With equal width items?

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>
like image 663
ell175 Avatar asked Sep 25 '20 10:09

ell175


2 Answers

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>
like image 187
Temani Afif Avatar answered Oct 07 '22 00:10

Temani Afif


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%;
}
like image 25
MohammdReza Keikavousi Avatar answered Oct 07 '22 00:10

MohammdReza Keikavousi