nth-child选择器用于重复定位第1和第4,以及第2和第3个元素

时间:2018-01-29 12:12:06

标签: css css-selectors

我正在尝试用nth-child做一个css选择器来创建类似的东西,但我认为它不可能。

主要问题是重复这个。

enter image description here

  a:nth-child(3n+1) {
    grid-column: 1/4;
    border: 1px solid red;
  }

  a:nth-child(3n+2) {
    grid-column: 4/13;
    border: 1px solid blue;
  }
<div class="box-container">
 <a href="#">1</a>
 <a hred="#">2</a>
<a href="#">3</a>
 <a hred="#">4</a>
 <a href="#">1</a>
 <a hred="#">2</a>
<a href="#">3</a>
 <a hred="#">4</a>
</div>

更新 那怎么样?也许更好地使用grid-area-template?还是第n个孩子?或根本不可能? enter image description here

下面的图片

2 个答案:

答案 0 :(得分:2)

您可以将:nth-child用作

.item:nth-child(4n) {
  grid-column: 10/13;
  border: 1px solid red;
}

.item:nth-child(4n+1) {
  grid-column: 1/4;
  border: 1px solid red;
}

.item:nth-child(4n+2) {
  grid-column: 4/13;
  border: 1px solid blue;
}

.item:nth-child(4n+3) {
  grid-column: 1/10;
  border: 1px solid blue;
}

.item {
  height: 100px;
}

.grid {
  display: grid;
  grid-gap: 10px;
}
<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>

答案 1 :(得分:0)

  a:nth-child(4n+1) {
    grid-column: 1/5;
    border: 1px solid red;
  }

  a:nth-child(4n+2) {
    grid-column: 5/13;
    border: 1px solid blue;
  }

  a:nth-child(4n+3) {
    grid-column: 1/9;
    border: 1px solid green;
  }

  a:nth-child(4n+4) {
    grid-column: 9/13;
    border: 1px solid yellow;
  }