css nth-child()检查板模式

时间:2018-05-25 14:26:35

标签: css flexbox css-selectors

想象一下,网格有四列和n行。每个第二个元素应该具有与另一个元素不同的颜色。种类the basic pattern,但只有四列。

我需要一个单亲,其上有display: flex。我尝试调整链接的示例,但我无法使其正常工作。

1 个答案:

答案 0 :(得分:1)

这非常简单,因为模式重复超过2行4,你只需要将样式应用于8n + i以获得方格图案:

.flex {
  display: flex;
  width: 400px;        /* width of four squares */
  flex-direction: row;
  flex-wrap: wrap;
}

.square {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  box-sizing: border-box;
}

.square:nth-child(8n+1),
.square:nth-child(8n+3),
.square:nth-child(8n+6),
.square:nth-child(8n+8) {
    background:black;
}
.square:nth-child(8n+2),
.square:nth-child(8n+4),
.square:nth-child(8n+5),
.square:nth-child(8n+7) {
    background:white;
}
<div class="flex">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>