I want to achieve a layout looking like the following:
In other words, the last item takes up the "remaining space" in away that the other items are centered as if item 3 is equally sized to item 1 and 2. The closest I can get to this is this layout:
I've also tried setting height: 100%
on the last item, which of course doesn't work since that pushes item 1 and 2 to the top. Here's the snippet that I don't know how to finish:
/* Default values are skipped */
.container {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.item {
background: red;
}
.item-fill {
background: yellow;
/* What should go in here? */
}
<div class="container">
<div class="item">
First item
</div>
<div class="item">
Second item
</div>
<div class="item-fill">
Third item which should fill up the rest of the parent space without pushing the first and second item upwards
</div>
</div>
It might be that this cannot be solved with flex-box alone and needs hack, but I would be thankful to whomever can come up with the most simple solution.
Thank you.
You can use the flex-grow property to force an item to fill the remaining space on the main axis of a flex container. The item will expand as much as possible and occupy the free area.
To center the inner div element we will make the parent a flex container. By adding the display: flex; property we make the section element a flex container allowing us to adjust the layout of the div which is now a flex item. To center out item horizontally we use the justify-content: center; .
Simply add a pseudo element that has a value of flex-grow: 1;
(before the other items in your container) and set the same flex-grow value to .item-fill
.
The pseudo-element (.container:before
here), will fill the top part of the container as much as it can and the other item with a flex-grow
value will fill the rest. The two other items will be as small as their content.
/* Default values are skipped */
.container {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.container:before {
content: "";
}
.container:before,
.item-fill {
flex: 1;
}
.item {
background: red;
}
.item-fill {
background: yellow;
}
<div class="container">
<div class="item">
First item
</div>
<div class="item">
Second item
</div>
<div class="item-fill">
Third item which should fill up the rest of the parent space without pushing the first and second item upwards
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With