The arrangement of columns can be a bit challenging. If you refer to the specification regarding column-width
, you will come across the following:
describes the optimal column width. The actual column width may be wider (to fill the available space), or narrower (only if the available space is smaller than the specified column width). source
To observe this, remove the fixed width from the elements and resize the container:
.flex-container {
width: 400px;
border: 1px solid blue;
columns: 120px;
padding: 10px;
overflow:hidden;
resize:horizontal;
}
.flex-item {
background: OliveDrab;
padding: 5px;
height: 100px;
line-height: 100px;
color: white;
text-align: center;
break-inside: avoid-column;
}
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
</div>
You'll notice that the gap remains consistent but the column widths adjust accordingly.
For a solution, consider using CSS grid with fixed column width. Define the grid column's width as the sum of gap + column width, allowing the container to accommodate all the columns evenly:
Resize the screen to see the result:
.container {
display:grid;
grid-template-columns:repeat(auto-fit,140px); /* 120 + 20 */
overflow: hidden;
resize: horizontal;
border: 1px solid blue;
}
.flex-container {
grid-column:1/-1;
column-width: 120px;
column-gap: 20px;
padding: 10px;
}
.flex-item {
background: OliveDrab;
padding: 5px;
height: 100px;
line-height: 100px;
color: white;
text-align: center;
break-inside: avoid-column;
}
<div class="container">
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
<div class="flex-item">6</div>
<div class="flex-item">7</div>
<div class="flex-item">8</div>
<div class="flex-item">9</div>
<div class="flex-item">10</div>
</div>
</div>