Set two flex items side by side in a flexbox column
The layout is fairly simple with flexbox. You don't need flex-direction: column
.
Just use flex-direction: row
with flex-wrap: wrap
.
Then make each element long enough to occupy a full row.
Reduce the flex-basis
on the elements that are to share a row.
.flex-column {
display: flex;
flex-wrap: wrap;
}
.column-item {
flex: 1 0 61%; /* flex-grow, flex-shrink, flex-basis */
margin: 2px;
background-color: lightgreen;
}
.column-item:nth-of-type(4),
.column-item:nth-of-type(5) {
flex-basis: 40%;
}
<div class="flex-column">
<div class="column-item">a</div>
<div class="column-item">b</div>
<div class="column-item">c</div>
<div class="column-item">d</div>
<div class="column-item">e</div>
</div>
With flex-grow: 1
defined in the flex
shorthand, there's no need to use calc()
.
Since flex-grow
will consume free space on the row, flex-basis
only needs to be large enough to enforce a wrap. In this case, with flex-basis: 61%
, there's plenty of space for the margins, but never enough space for a second item.
There's an even simpler and more efficient solution using CSS Grid:
.flex-column {
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 5px;
}
.column-item:nth-of-type(-n + 3) {
grid-column: span 2;
}
.column-item {
background-color: lightgreen;
}
<div class="flex-column">
<div class="column-item">a</div>
<div class="column-item">b</div>
<div class="column-item">c</div>
<div class="column-item">d</div>
<div class="column-item">e</div>
</div>
I don't think it is possible once you have given your parent the flex-direction:column;
property, alternatively you can enable flex-wrap:wrap
and control the width of elements using the flex-basis
property. This allows you to achieve the effect you want without altering your html structure.
.flex-column {
display: flex;
flex-wrap:wrap;
}
.flex-column .column-item {
flex-basis:100%;}
.flex-column .column-item:nth-of-type(4),
.flex-column .column-item:nth-of-type(5) {
flex-basis:50%;
}
<div class="flex-column">
<div class="column-item">a</div>
<div class="column-item">b</div>
<div class="column-item">c</div>
<div class="column-item">d</div>
<div class="column-item">e</div>
</div>