本文介绍了CSS nth-child应用奇偶规则,但每4项切换一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个divs的列表,该列表与一个类连续出现4个,我想创建一个棋盘背景样式,表示:

I have a list of divs that appear 4 in a row with a class and I would like to create a checkerboard background style, meaning:

  • divs和奇数divs应用不同的背景颜色
  • 将每行的奇偶数切换为偶数
  • Apply a different background color for odd and even divs
  • Switch the odd-even to even-odd for each line

我已经尝试过

.boxwrapper:nth-child(2n-1), .boxwrapper:nth-child(2n) {
    background:#ff0000;
}
.boxwrapper:nth-child(4n-2), .boxwrapper:nth-child(4n-3) {
    background:#0000ff;
}

,它适用于奇偶div,但无法使其每4个项目切换一次.如果我能得到正确的结果,我正在研究4n-1、4n + 1的东西!

and it works fine for odd-even divs but cant get it to switch every 4 items. I'm headaching over the 4n-1, 4n+1 stuff, if I could get that right voila!

结果应如下所示:

推荐答案

演示

http://jsfiddle.net/mykhA/1/

<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>​

CSS

.container {
    width: 100px;
    height: 100px;
}

.line {
    width: 100px;
    height: 25px;
}

.box {
    width: 25px;
    height: 25px;
    float: left;
}

.box:nth-child(8n+2) {
    background-color: red;
}

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

.box:nth-child(8n+7) {
    background-color: red;
}

.box:nth-child(8n+1) {
    background-color: blue;
}

.box:nth-child(8n+3) {
    background-color: blue;
}

.box:nth-child(8n+6) {
    background-color: blue;
}

.box:nth-child(8n) {
    background-color: blue;
}
​

这篇关于CSS nth-child应用奇偶规则,但每4项切换一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 17:34