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

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

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;
}
<div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

回答

继格局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;
}

在现代浏览器上,您还可以: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;
}

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

.box {
  background-color:green;
}

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


以上是使用cssnth-child伪代码重复颜色模式的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>