I have a flex container that contains several items whose height can vary depending on their content.
Because the items' heights can vary and I have no way of knowing how tall the tallest one could get, I can't set a fixed height on the container.
But I want the flex items to wrap. How can I do this without setting a fixed height on the container?
I don't want to hardcode which items go in which columns because I don't know how much height each item will take up, and even the number of items isn't fixed, depending on the data being viewed there may be more or less items rendered.
EDIT: this isn't a duplicate because my question isn't an open-ended how do I make a masonry layout
, it's a specific question for how to make a flex container be as short as it needs to be to fit the tallest child element. Yes, an answering to this question would enable masonry layouts, but a generic answer for how to create a masonry layout wouldn't be a sufficient answer to this question.
.page {
width: 100%;
display: flex;
flex-direction: column;
gap: 10px;
align-items: stretch;
}
.stuff {
height: 50px;
background-color: #add8e6;
}
/* How do I make this container be as short as possible by making the items wrap eagerly? */
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 10px;
}
.item {
width: 100px;
background-color: #f00;
}
p {
font-family: sans-serif;
}
<div class="page">
<div class="stuff"></div>
<div class="stuff"></div>
<p> The below items should wrap as early as possible so that the container is as short as possible</p>
<div class="container">
<div class="item" style="height: 84.2100389510485px;"></div>
<div class="item" style="height: 191.92293493979756px;"></div>
<div class="item" style="height: 173.77855481317093px;"></div>
<div class="item" style="height: 191.53106857845174px;"></div>
<div class="item" style="height: 25.255845195229462px;"></div>
<div class="item" style="height: 139.09297679242505px;"></div>
<div class="item" style="height: 151.36271062612596px;"></div>
<div class="item" style="height: 95.27193455143049px;"></div>
<div class="item" style="height: 168.37033024481275px;"></div>
<div class="item" style="height: 161.5719425642975px;"></div>
</div>
<div class="stuff"></div>
<div class="stuff"></div>
</div>
Codepen link illustrating the problem