使用 css nth-child 伪代码重复颜色模式

asl*_*tor 0 html css

我已经构建了一个示例页面,如下所示。但是框颜色是通过选择特定框来分配的。

body, *{
  box-sizing: border-box;
}
.container{
  width:200px;
  margin:0px auto;
}
.box{
  width:100px;
  height:100px;
  float:left;
}
.box:nth-child(1){
  background-color:red;
}
.box:nth-child(2){
  background-color:green;
}
.box:nth-child(3){
  background-color:green;
}
.box:nth-child(4){
  background-color:red;
}
.box:nth-child(5){
  background-color:red;
}
.box:nth-child(6){
  background-color:green;
}
.box:nth-child(7){
  background-color:green;
}
.box:nth-child(8){
  background-color:red;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

我想更改它,以便每当添加新框或删除任何框时,红绿色模式不会中断。我怎样才能做到这一点?

fca*_*ran 5

继格局4n4n+1 .box孩子是红色的,而4n+24n+3 .box孩子们的绿色

body, *{
  box-sizing: border-box;
}
.container{
  width:200px;
  margin:0px auto;
}
.box{
  width:100px;
  height:100px;
  float:left;
}

.box:nth-child(4n), 
.box:nth-child(4n + 1) {
  background-color:red;
}

.box:nth-child(4n + 2), 
.box:nth-child(4n + 3) {
  background-color:green;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

在现代浏览器上,您还可以:nth-child使用新的:is伪类对伪类进行分组

.box:is(:nth-child(4n), :nth-child(4n + 1)) {
  background-color:red;
}

.box:is(:nth-child(4n + 2), :nth-child(4n + 3)) {
  background-color:green;
}
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找更短的代码,只需默认green为所有.box元素分配背景,然后将其更改为red仅 on4n4n+1元素。

.box {
  background-color:green;
}

.box:nth-child(4n), 
.box:nth-child(4n + 1) {
  background-color:red;
}
Run Code Online (Sandbox Code Playgroud)