CSS - 如何使用 li:nth-child 将列表 <li> 分成 3 列?
CSS - How can I divide a list <li> in 3 columns using li:nth-child?
有 6 个元素,我希望它们是这样的:
- First - Third - Fifth
- Second - Fourth - Sixth
我试过这样的事情:
li:nth-child(6n+1) {
float: left;
width: 30%;
}
li:nth-child(2n+3) {
float: right;
width: 30%;
}
这是使用 CSS 网格的布局示例;正如@NickG 所提到的,the documentation 值得一读,因为它是一个非常有用的学习概念。
下面,我为每个 div 分配了一个 grid-area
名称,并用它来引用您用 grid-template-areas
描述的布局。
.container { display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 8px 8px;
grid-auto-flow: row;
grid-template-areas:
"one three five"
"two four six";
}
.container * {
width: 50px;
height: 50px;
background: orange;
}
.one { grid-area: one; }
.two { grid-area: two; }
.three { grid-area: three; }
.four { grid-area: four; }
.five { grid-area: five; }
.six { grid-area: six; }
<div class="container">
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="six">6</div>
</div>
您可以像下面这样使用 CSS 网格:
ul {
display: grid;
list-style: none;
grid-auto-flow: column;
grid-template-rows: 1fr 1fr;
margin:0;
padding:0;
text-align:center;
}
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>
有 6 个元素,我希望它们是这样的:
- First - Third - Fifth
- Second - Fourth - Sixth
我试过这样的事情:
li:nth-child(6n+1) {
float: left;
width: 30%;
}
li:nth-child(2n+3) {
float: right;
width: 30%;
}
这是使用 CSS 网格的布局示例;正如@NickG 所提到的,the documentation 值得一读,因为它是一个非常有用的学习概念。
下面,我为每个 div 分配了一个 grid-area
名称,并用它来引用您用 grid-template-areas
描述的布局。
.container { display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 8px 8px;
grid-auto-flow: row;
grid-template-areas:
"one three five"
"two four six";
}
.container * {
width: 50px;
height: 50px;
background: orange;
}
.one { grid-area: one; }
.two { grid-area: two; }
.three { grid-area: three; }
.four { grid-area: four; }
.five { grid-area: five; }
.six { grid-area: six; }
<div class="container">
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="six">6</div>
</div>
您可以像下面这样使用 CSS 网格:
ul {
display: grid;
list-style: none;
grid-auto-flow: column;
grid-template-rows: 1fr 1fr;
margin:0;
padding:0;
text-align:center;
}
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>