I'm using the CSS multi-column layout for this layout:
I want the content to use as many columns as possible. It does that in the above image, but when there's only 3 items, it does the following:
I would like the box "3" to be to the right of box "2". Is that possible?
EDIT: looking for a general solution (this is a simplified example, we don't know the heights of the container or elements in advance).
EDIT 2: if there's a better way than using multi-column (perhaps grid?), we'd use that.
Here's the HTML/CSS (or jsfiddle here):
.container {
column-width: 120px;
column-gap: 20px;
padding: 10px;
width: 600px;
height: 250px;
border: 1px solid blue;
}
.item {
background: #2371f3;
padding: 5px;
height: 100px;
width: 100px;
color: white;
break-inside: avoid;
/* Workaround for Firefox bug (https://stackoverflow.com/a/7785711/2223706) */
overflow: hidden;
border: 1px solid darkblue;
}
.longer {
height: 220px; /* Decreasing this to 200px makes #2 and #3 no longer stack. */
}
<div class="container">
<div class="item longer">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
in chrome you can add this in your stylesheet at the end
.item:nth-child(n+3):last-child {
background: #000;
break-before: column;
}
if you have 3 items, the 3th item moves to the right, if a forth comes in then it goes back under 2nd.
if you have 5 items, the 5th item moves to the right, if a sixth comes in then it goes back under 4th.
but I cannot make it work on firefox, I think the column/break compatibility still is not that good on mozilla
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