使用单独父项中的伪类的交替元素的样式

时间:2013-06-14 16:17:14

标签: css html pseudo-class css-selectors

我有几个div元素,我想在其中替换另一组div个样式。因此,基本上将孩子的风格改为交替的背景颜色,如下所示:

HTML

<article class="post"> <!--first post-->
  <div class="title">Title Here</div>
  content here
</article>

<article class="post"> <!--second post-->
  <div class="title">Title Here</div>
  content here
</article>

CSS

div.title:nth-of-type(even) {
   background-color: #F00;
}
div.title:nth-of-type(odd) {
   background-color:#00F;
}

有没有办法做到这一点,因为我知道使用css替换样式它必须在父级内。或者,如果没有,我可以使用任何jquery脚本吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

nth-of-type总是在检查父母中元素的位置。因此,您的div's始终是.post的第一个孩子。这就是它无法运作的原因。

但你可以查看它的父母的孩子位置。就像那样:

.post:nth-of-type(even) div.title{}
.post:nth-of-type(odd) div.title{}

答案 1 :(得分:1)

你应该使用

article.post:nth-of-type(even) .title

这样做很好。

<强> jsFiddle


另外,请尝试远离过度限定的CSS选择器,例如div.title,如CSS Wizardy的this文章中所述。基本上,此实例中的.title肯定在article.post范围内,因此您也无需添加div

  

资格过高的选择器使浏览器的工作量超出了需要   并耗尽其时间;让你的选择器更精简,更高效   削减不必要的比特。