我有以下HTML:
<section class="history">
<div class="asked">
<h1 class="user-show-tab-title">Questions</h1>
<div>
<ul class="question-index-false"></ul>
</div>
</div>
<div class="answered">
<h1 class="user-show-tab-title">Answers</h1>
<div>
<ul class="question-index-false"></ul>
</div>
</div>
</section>
我正在拼命尝试使用类&#34; user-show-tab-title&#34;选择第二个h1
元素并设置其样式。 (带有&#34;答案&#34;的那个)
但出于某种原因.user-show-tab-title:nth-of-type(1)
选择了它们,.user-show-tab-title:nth-of-type(2)
没有选择任何内容。
是什么给出了?
答案 0 :(得分:6)
那是因为它们都是div中第一个类型h1
。 nth-of-type
仅适用于直接的子女关系。
另请注意,nth
相关选择器从1开始,因此要选择第二个选择器,您将使用2而非1。
我不知道您的实际HTML,但是对于您拥有的内容,您可以使用
.answered .user-show-tab-title
如果您真的想使用nth-of-type
,可以使用以下方法。我正在插入一些虚拟<p>
,否则<section>
的所有孩子都属于同一类型。
.history div:nth-of-type(1) .user-show-tab-title {
background-color: lightblue;
}
.history div:nth-of-type(2) .user-show-tab-title {
background-color: #eee;
}
<section class="history">
<p>Dummy paragraph</p>
<p>Dummy paragraph</p>
<div class="asked">
<h1 class="user-show-tab-title">Questions</h1>
<div>
<ul class="question-index-false"></ul>
</div>
</div>
<p>Dummy paragraph</p>
<p>Dummy paragraph</p>
<p>Dummy paragraph</p>
<div class="answered">
<h1 class="user-show-tab-title">Answers</h1>
<div>
<ul class="question-index-false"></ul>
</div>
</div>
</section>
答案 1 :(得分:2)
为什么不选择.answered h1
? :)你的选择器不起作用,因为他们在不同的父母之下。