CSS columns with left-right flow

谁都会走 提交于 2019-12-24 10:38:28

问题


Let's say I have a div which will contain a set of elements (divs), which may have different heights, but all of them will have the same width.

I've achieved this currently with isotope + masonry, but since some browsers already support CSS3 multi-columns, I was hoping to have a only-CSS solution for these browsers, falling back to Javascript for the rest.

This is the CSS I've been trying:

.div-of-boxes {
  -webkit-column-count: 3;
  -webkit-column-gap:   10px;
  -moz-column-count:    3;
  -moz-column-gap:      10px;
  column-count:         3;
  column-gap:           10px;
}

However, this makes the flow of the elements to be top-down left-right. I'd like instead a left-right top-down flow. This is an example of what I'd like:

1 2 3
4 5 6
7 8 9

But this is what I get:

1 4 7
2 5 8
3 6 9

In Flow multi-column elements left-right before top-down something similar is asked, but I'm not satisfied with the answer, and it won't work with elements of different height. Is this possible at all with CSS columns, or is it a limitation?


回答1:


The multi-column specification offers no property to change the distribution of elements among the columns: http://www.w3.org/TR/css3-multicol/. Such a property seems to go against what the module was designed for (recreating how newspaper or magazine articles are laid out).

None of the other pure CSS solutions will allow you to achieve the effect you are looking for.




回答2:


If your layout is always going to be 3 columns wide, you could try using the nth selector on your internal divs.
You could do this by clearing your 4th item.

#container {
    overflow: hidden;
    width: 440px;
}
#container div {
    background-color: gray;
    width: 110px;
    margin: 5px;
    float: left;
}
#container div:nth-child(4) {
    clear: both;
}
<div id="container">
    <div id="widget1">1</div>
    <div id="widget2">2</div>
    <div id="widget3">3</div>
    <div id="widget4">4</div>
    <div id="widget5">5</div>
    <div id="widget6">6</div>
    <div id="widget7">7</div>
    <div id="widget7">8</div>
</div>

JS Fiddle




回答3:


You can use jQuery to rearrange items in columns. In case of 2 cols it would be:

$('.your-columns-container .your-item:nth-child(even)').appendTo('.your-columns-container');

https://jsfiddle.net/hzvp7sgf/

And something more complicated for 3 columns:

$('.your-columns-container .your-item:nth-child(3n - 1)').addClass('container-col2');
$('.your-columns-container .your-item:nth-child(3n)').addClass('container-col3');

$('.container-col2').appendTo('.your-columns-container').removeClass('container-col2');
$('.container-col3').appendTo('.your-columns-container').removeClass('container-col3');

https://jsfiddle.net/d4LeLyu5/



来源:https://stackoverflow.com/questions/27976359/vertical-vs-horizontal-masonry-css-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!