用语言很难解释这一点。
我正在尝试使用flexbox做一个看起来像这样的列表:
html - 如何制作具有两行但将元素分为两个子列的flexbox布局?-LMLPHP



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>





有任何想法吗?

最佳答案

您可以使用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代码段的宽度:)

07-24 18:58
查看更多