选择潜在无限子女列表的第n个孩子

时间:2017-09-23 18:06:26

标签: html css math sass css-grid

我有一个网格布局 - 每行4列。我正在使用CSS网格布局。

假设可能存在无数个项目。

<div class="grid">
    <div class="item"></div>
    <div class="item"></div>
    <!-- ... -->
</div>

如果项目数量可能无限,我怎么能选择每行的两个中间项目。例如,我需要选择前三行:

nth-child(2)nth-child(3)nth-child(6)nth-child(7)nth-child(10)nth-child(11)

我可以将样式硬编码到一个特定的数字,假设它不是一个无穷大的数字,但如果有一种方法可以动态地进行,我宁愿这样做。

enter image description here

3 个答案:

答案 0 :(得分:6)

您可以使用.item:nth-child(4n+2)定位每四个孩子(从2个孩子开始)和.item:nth-child(4n+3)以每四个孩子为目标(从第3个孩子开始)。这是一个例子:

.item:nth-child(4n+2),
.item:nth-child(4n+3) {
  color: red;
  background-color: yellow;
}
<div class="grid">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
    <div class="item">11</div>
    <div class="item">12</div>
</div>

答案 1 :(得分:2)

使用nth-child(xN+y)语法...

&#13;
&#13;
.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 25px;
}

.box {
  padding: 1em;
  border: 1px solid grey;
}

.container :nth-child(4n+2) {
  background: red;
}

.container :nth-child(4n+3) {
  background: blue;
}
&#13;
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

以下是js解决方案:

&#13;
&#13;
var items = document.getElementsByClassName('item');
for (i = 0; i < items.length; i++) {
  if(i % 2 === 0 && i % 4 === 0) {
    var el1 = items[i + 1];
    var el2 = items[i + 2];
    if (el1)
      el1.style.backgroundColor = "red";
    if (el2)
      el2.style.backgroundColor = "red";
  }
}
&#13;
.grid {
  display:grid;
  grid-template-columns: 100px 100px 100px 100px;
}

.item {
  border:1px solid black;
  padding:20px;
  margin:4px;
}
&#13;
<div class="grid">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
&#13;
&#13;
&#13;