Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have content in multi-columnn layout use all columns

I'm using the CSS multi-column layout for this layout:

enter image description here

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:

enter image description here

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>
like image 506
Garrett Avatar asked Oct 14 '22 22:10

Garrett


1 Answers

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

like image 144
Tch Avatar answered Oct 24 '22 05:10

Tch