如何选择同一类的一定数量的连续元素中的最后一个?

时间:2011-07-17 14:25:05

标签: css css3 css-selectors

我目前正在尝试将每个标题的边框颜色设置为彩虹中的不同颜色,以便此HTML的第一个标题样式为maroon,第二个orange,第三个olive

<h2 class="rh">Heading 1</h2>
<p>Text</p>
<h2 class="rh">Heading 2</h2>
<p>Text</p>
<h2 class="rh">Heading 3</h2>
<p>Text</p>

我目前的CSS就是这个。然而,这真的是无足轻重的。还有更好的方法吗?

.rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh {
    border-bottom: 2px solid maroon;
}
.rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh {
    border-bottom: 2px solid orange;
}
.rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh {
    border-bottom: 2px solid olive;
}
.rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh {
    border-bottom: 2px solid green;
}
.rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh {
    border-bottom: 2px solid navy;
}
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh,
.rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh ~ .rh {
    border-bottom: 2px solid purple;
}

1 个答案:

答案 0 :(得分:2)

编辑#a_lot:

正如我们在评论中所建立的那样,不需要类名,我们可以用于大多数主流浏览器,而MSIE&gt; = 9:

.r > h2:nth-of-type(6n+1){
    border-bottom: 2px solid maroon;
}
.r > h2:nth-of-type(6n+2){
    border-bottom: 2px solid orange;
}
.r > h2:nth-of-type(6n+3){
    border-bottom: 2px solid olive;
}
.r > h2:nth-of-type(6n+4){
    border-bottom: 2px solid green;
}
.r > h2:nth-of-type(6n+5){
    border-bottom: 2px solid navy;
}
.r > h2:nth-of-type(6n+6){
    border-bottom: 2px solid purple;
}

以下答案是错误的,但作为参考,以确定它是错误的:p.classname:nth-of-type(3n)之类的内容选择两者第3 p段元素具有类classname,而不是每隔3 p具有类classname ,正如我所期望的那样。< /德尔>


在遥远的未来,你可以使用nth-of-type,大约在常用MSIE 9和MSIE6 / 7/8退出的时候。所以,现在:你失控了。