如何制作具有两行但将项目分为两个子列的flexbox布局?

时间:2018-10-26 13:32:00

标签: html css css3 flexbox

很难用语言来解释。 我正在尝试使用flexbox做一个看起来像这样的列表: enter image description here

ul {
  display:flex;
  width:100%;
}

li {
  list-style:none;
  width: 200px; height: 140px;
  background-color:blue;
  color:#fff;
}
li:nth-child(odd) {
 /*?*/
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以使用order和一些nth-child选择器来做到这一点。

要选择每2个元素(您的3-4、7-8个元素),可以使用li:nth-child(4n), li:nth-child(4n-1)。例如,如果n = 1,则可以选择4*14*1-1。因此,第四和第三元素。依此类推。

要选择其他元素(在您的示例中不是必需的,但很高兴知道),请使用li:nth-child(4n-2),li:nth-child(4n-3)

然后,通过设置order:1来更改它们在flex容器中的顺序。默认值为0。在这里了解更多-> flex order

请参见下面的代码段

li:nth-child(4n),
li:nth-child(4n-1) {
  background: Red;
  order: 1;
}

li:nth-child(4n-2),
li:nth-child(4n-3) {
  background: blue;
}

ul {
  display: flex;
  flex-wrap: wrap;
}

li {
  list-style: none;
  width: calc(25% - 10px);
  height: 140px;
  background-color: blue;
  color: #fff;
  margin: 0 5px;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

OBS 我在width: calc(25% - 10px);上使用了li,因为200px x 4超出了SO代码段的宽度:)

答案 1 :(得分:-1)

ul {
display: flex;
flex-wrap: wrap;
list-style-type: none;
width: 450px;
}

li {
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 34px;
height: 70px;
width: 100px;
margin: 3px;
background: dodgerblue;
border: solid 1px black;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
   
 </ul>