Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

css - 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>
question from:https://stackoverflow.com/questions/65928416/have-content-in-multi-columnn-layout-use-all-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...