0

我有几个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,我可以使用任何脚本吗?

谢谢你。

4

2 回答 2

2

你应该使用

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

这种方式工作得很好。

jsFiddle


此外,请尽量远离过度限定的 CSS 选择器,如CSS Wizardydiv.title这篇文章中所解释的。基本上,.title在这种情况下,肯定是在 内article.post,所以你不需要添加div太。

过度限定的选择器使浏览器比它需要的工作更辛苦,并且耗尽了它的时间;通过删除不必要的部分,使您的选择器更精简、更高效。

于 2013-06-14T16:34:01.933 回答
1

nth-of-type总是在他的父母中检查元素的位置。因此,您div's始终是.post. 这就是为什么它不起作用。

但是您可以检查其父级的子级位置。就像这样:

.post:nth-of-type(even) div.title{}
.post:nth-of-type(odd) div.title{}
于 2013-06-14T16:28:17.390 回答