我正在尝试使用 css 制作一个包含 3 列的网格视图。我有 2 列系统使用以下代码,但我似乎无法正确处理 3 列:
#container{background-color:#aaa;margin: 0 auto;height:500px; width: 200px;}
.box{background-color:white;
border:1px solid black;
margin: 2%;
width:45%;
display:block;
float:left;
box-sizing: border-box;
}
.box:nth-child(2n + 0) { float: right; }Run Code Online (Sandbox Code Playgroud)
<div id='container'>
<div class='box' style="height:70px; background-color: red;">1</div>
<div class='box' style="height:130px; background-color: grey;">2</div>
<div class='box' style="height:90px;">3</div>
<div class='box' style="height:86px; background-color: orange;">4</div>
<div class='box' style="height:110px; background-color: green;">5</div>
<div class='box' style="height:40px;">6</div>
</div>Run Code Online (Sandbox Code Playgroud)
这是 jsfiddle:https ://jsfiddle.net/jfnvt9o3/
有没有办法只用 css 来实现以下目标,如果是这样,如何实现?
小智 6
如果您可以重新排序 HTML,则可以使用多列的解决方案。在其他情况下,我认为没有 JavaScript 是不可能的。
#container {
background-color: #aaa;
margin: 0 auto;
height: 500px;
width: 500px;
-moz-column-count: 3;
-webkit-column-count: 3;
column-count: 3;
-moz-column-gap: 10px;
-webkit-column-gap: 10px;
column-gap: 10px;
}
.box {
background-color: white;
border: 1px solid black;
width: 100%;
margin: 10px 0;
display: inline-block;
box-sizing: border-box;
}Run Code Online (Sandbox Code Playgroud)
<div id='container'>
<div class='box' style="height:70px; background-color: red;">1</div>
<div class='box' style="height:86px; background-color: orange;">4</div>
<div class='box' style="height:130px; background-color: grey;">2</div>
<div class='box' style="height:110px; background-color: green;">5</div>
<div class='box' style="height:90px;">3</div>
<div class='box' style="height:40px;">6</div>
</div>Run Code Online (Sandbox Code Playgroud)
尝试这个 javascript 库 - 没有正确的(跨浏览器)仅 css 解决方案:
您也可以尝试 css 列:
https://css-tricks.com/almanac/properties/c/columns/