如何在html中选择奇数元素?

时间:2015-09-16 11:52:57

标签: html css css-selectors

我有一个显示一些帖子的网站。每个帖子都有标题类和内容类。我想将奇数无标题的颜色改为红色,偶数编号为黑色。

            <div class="category_header">
                <h2><a href="#">Heading</a></h2>
            </div> 
            <div class="single-post">           
                <p></p>
            </div>
上面给出的是我的html代码的格式。所以通过跟随link我试过这样的事情

.category_header:nth-child(odd) {
background: red;
}

现在所有标题颜色都变为红色。一些帮助将不胜感激。 感谢

2 个答案:

答案 0 :(得分:4)

  

我想将奇数标题的颜色更改为红色,偶数编号的标题为黑色。

.category_header:nth-of-type(4n+1) h2 a {
  color: red;
}

另外,如果没有干预要素:

.category_header:nth-child(4n+1) h2 a {
  color: red;
}

&#13;
&#13;
* {
  margin: 0;
}
a {
  color: black;
  text-decoration:none;
}
.category_header:nth-of-type(4n+1) h2 a {
  color: red;
}
&#13;
<div class="category_header">
  <h2><a href="#">Heading 1</a></h2>

</div>
<div class="single-post">
  <p>Lorem ipsum dolor.</p>
</div>
<div class="category_header">
  <h2><a href="#">Heading 2</a></h2>

</div>
<div class="single-post">
  <p>Lorem ipsum dolor sit amet.</p>
</div>

<div class="category_header">
  <h2><a href="#">Heading 3</a></h2>

</div>
<div class="single-post">
  <p>Lorem ipsum dolor sit amet.</p>
</div>

<div class="category_header">
  <h2><a href="#">Heading 4</a></h2>

</div>
<div class="single-post">
  <p>Lorem ipsum dolor sit amet.</p>
</div>

<div class="category_header">
  <h2><a href="#">Heading 5</a></h2>

</div>
<div class="single-post">
  <p>Lorem ipsum dolor sit amet.</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您应该使用:nth-of-type(XX)

&#13;
&#13;
.category_header:nth-of-type(odd) {
  background: red;
}
&#13;
<div class="category_header">
  <h2><a href="#">Heading</a></h2>
</div>
<div class="single-post">
  <p></p>
</div>
&#13;
&#13;
&#13;