将CSS背景颜色应用于第3个孩子3到10的最简单方法

时间:2014-07-02 06:12:07

标签: html css css3 css-selectors

我想将CSS背景颜色应用于第3个孩子的第3个

    <div class="roundperiodbg" id="roundPeriod1" title="PERIOD 1"></div>
    <div class="roundperiodbg" id="roundPeriod2" title="PERIOD 1"></div>

    <div class="roundperiodbg" id="roundPeriod3" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod4" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod5" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod6" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod7" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod8" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod9" title="PERIOD 2"></div>
    <div class="roundperiodbg" id="roundPeriod10" title="PERIOD 2"></div>

    <div class="roundperiodbg" id="roundPeriod11" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod12" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod13" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod14" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod15" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod16" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod17" title="PERIOD 3"></div>
    <div class="roundperiodbg" id="roundPeriod18" title="PERIOD 3"></div>

这有效,但CSS中有更简单的方法吗?

.roundperiodbg:nth-child(3), .roundperiodbg:nth-child(4), ..... .roundperiodbg:nth-child(10) {
        background : green;

}

5 个答案:

答案 0 :(得分:14)

您可以使用两个:nth-child()选择器来创建这样的范围:

.roundperiodbg:nth-child(n+3):nth-child(-n+10){
     background : green;
}

请参阅 demo fiddle

说明:

:nth-child(n+3)选择索引等于或大于3的所有元素

------
n | i
------
0 | 3
------
1 | 4
------
2 | 5
------
3 | 6
------
..| ..

:nth-child(-n+10)选择索引等于或小于10的所有元素

------
n | i
------
0 | 10
------
1 | 9
------
2 | 8
------
3 | 7
------
..| 1

当您在同一CSS规则中应用两者时,元素必须匹配两个条件,因此它仅适用于索引在3到10之间的元素。


另外,您可以查看this link以了解:nth-child()选择器的更多精彩用法。 感谢@Rajaprabhu

答案 1 :(得分:0)

为什么不创建一个新类,如:

.roundperiodbg-green {
   background: green;
}

并将其应用于所有需要此样式的div?

答案 2 :(得分:0)

创建一个容器,将所有项目放入容器中。并使用下面的css代码:

.container>div:nth-child(n+3){
  background : green;
}

Look at this fiddle

答案 3 :(得分:0)

试一下

    .roundperiodbg{ background:#333; height:10px; width:100%; margin:5px;}
    .roundperiodbg:nth-child(n + 4){ background:green;}

答案 4 :(得分:-1)

您可以使用以下代码 -

$('.roundperiodbg:gt(2):lt(10)').css('background','green');

在此:gt(n)中指定将选择第n个元素之后的任何元素,并且lt(n)指定在选择第n个元素之前的任何元素