I have two <div>
rows with display: flex;
each of them contains a couple of children <div>
items. In the example below, you can see that in the first row there a 2 items (green boxes labeled "item") which are flexed in the ratio 6/3
. In the second there are 4 items which are flexed in the ratio 2/2/2/3
.
Now I would expect the last item in each row (the ones with flex: 3;
) to be perfectly aligned, which it is, unless I add a gap: X px;
.
How can I include this gap
in the calculation so that the items with the same width are aligned based on their flex
property?
Or graphically simplified in the following snippet: How can I align the red borders?
.flex {
height: 50px;
display: flex;
gap: 20px; // <- malefactor that destroys my layout
}
.item {
background-color: green;
outline: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.item-2 {
flex: 2;
}
.item-3 {
flex: 3;
}
.item-6 {
flex: 6;
}
<div>
<div class="flex">
<div class="item item-6" style="border-right: 2px solid red;">item</div>
<div class="item item-3">item</div>
</div>
<div class="flex">
<div class="item item-2">item</div>
<div class="item item-2">item</div>
<div class="item item-2" style="border-right: 2px solid red;">item</div>
<div class="item item-3">item</div>
</div>
</div>
2
Answers
One of the multiple possible solutions is to wrap some of the items in another flex div.
See in the code bellow with the class
flex-item
:Another solution would involve the use of css grid, you can setup a grid with 9 columns and assign the column span accordingly:
With this solution you can also use
grid-gap: 20px
instead ofgrid-column-gap: 20px
if you want the same gap between the rows.The correct way is the usage of CSS-Grid. You simply divide the grid into a 9-column grid which automatically takes the gaps into account: