简体   繁体   English

如果有足够的空间,如何将div列表分为两列?

[英]How can I split a list of divs into two columns if there's enough space?

Let's say I have 8 divs. 假设我有8个div。 I want them to be split into two columns like this if there's enough space (via min-width ): 如果有足够的空间(通过min-width ),我希望将它们分成两列:

 1  5
 2  6
 3  7
 4  8

However, if I simply set display: inline-block , they instead get split like this, which is not what I want: 但是,如果我只是设置display: inline-block ,它们就会像这样分裂,这不是我想要的:

 1  2
 3  4
 5  6
 7  8

Ideally, I'm looking for a solution that allows for unequal sizes, so if there's only 6, but #1 and #2 are of double height, the result will look like this: 理想情况下,我正在寻找一种允许大小不相等的解决方案,因此,如果只有6个,但#1和#2的高度是两倍,结果将如下所示:

1  3
1  4
2  5
2  6

Is this possible in pure CSS? 在纯CSS中有可能吗? Or, if not, how can this be done in JS? 或者,如果没有,如何在JS中完成呢?

You can use CSS Columns to achieve this behavior: 您可以使用CSS列来实现此行为:

 html { font-size: 62.5%; } .columnWrapper div { display: inline-block; width: 100%; height: 10rem; color: #fff; text-align: center; font-size: 5rem; line-height: 10rem; background-color: #4caf50; margin-bottom: 0.5rem; } .columnWrapper { -webkit-column-count: 2; -moz-column-count: 2; column-count: 2; -webkit-column-gap: 0.5rem; -moz-column-gap: 0.5rem; column-gap: 0.5rem; width: 20%; margin: 0 auto; } @media screen and (max-width: 500px) { .columnWrapper { -webkit-column-count: 1; -moz-column-count: 1; column-count: 1; } } 
 <div class="columnWrapper"> <div>1</div ><div>2</div ><div>3</div ><div>4</div ><div>5</div ><div>6</div ><div>7</div ><div>8</div> </div> 

Or see this fiddle. 或者看这个小提琴。

For the case that there are only six elements, see this fiddle (same code). 对于只有6个元素的情况下,看到这个小提琴(相同的代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM