Reputation: 11
I want flex container with flex-direction
as column
, to order items in the flexbox to take up empty spaces dynamically.
I have 2 different types elements in my array:
Container height is fixed as well to fit two short items and one long item i.e. 220px;
If I have following items in my array:
Then, I want them to render as:
Is this possible with flex or what are the alternatives to achieve this king of layout for array of items?
Problem
Upvotes: 0
Views: 1145
Reputation: 126
Here's a working sandbox with a solution to your problem using grid.
The solution requires hard-coding at least some of the elements positions.
It involves the use of:
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(2, 1fr);
And setting specific locations to certain elements in the container:
grid-column: 3 / 4;
To handle the case of 3 elements in the container, the changes required are:
grid-template-columns: repeat(4, 1fr);
Into -->
grid-template-columns: repeat(2, 1fr);
p.s. according to CanIUse, grid has a 96.22% support across all browsers.
Upvotes: 1
Reputation: 115108
Other than using wrappers for your various elements flexbox is not your best option here.
CSS-Grid can manage it BUT you would have to specific where you want each item to be.
nth-child
can help here but briefly it would look something like this:
.wrap {
display: grid;
grid-template-columns: repeat(4, 100px);
grid-template-rows: repeat(2, 100px);
gap: 10px;
}
.item {
border: 1px solid grey;
display: grid;
place-items: center;
}
.tall {
grid-row: span 2;
}
.item:nth-child(4) {
grid-column: 3;
grid-row: 2;
}
.item:nth-child(5) {
grid-column: 1;
grid-row: 2;
}
<div class="wrap">
<div class="item">1</div>
<div class="item tall">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item tall">6</div>
</div>
Upvotes: 1