为什么 nth-of-type 不起作用?
Why doesn't nth-of-type work?
我有以下 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>
我正在拼命尝试 select 并使用 class "user-show-tab-title"(带有 "answers" 的那个)设置第二个 h1
元素的样式
但出于某种原因 .user-show-tab-title:nth-of-type(1)
select 两者都是,而 .user-show-tab-title:nth-of-type(2)
没有 select 任何东西。
什么给了?
那是因为它们都是 div 中类型 h1
的第一个。 nth-of-type
仅适用于直系子女关系。
另请注意,nth
相关的 select OR 从 1 开始,因此到 select 秒,您将使用 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>
你为什么不直接 select .answered h1
呢? :) 您的 selector 将无法工作,因为它们处于不同的 parents.
我有以下 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>
我正在拼命尝试 select 并使用 class "user-show-tab-title"(带有 "answers" 的那个)设置第二个 h1
元素的样式
但出于某种原因 .user-show-tab-title:nth-of-type(1)
select 两者都是,而 .user-show-tab-title:nth-of-type(2)
没有 select 任何东西。
什么给了?
那是因为它们都是 div 中类型 h1
的第一个。 nth-of-type
仅适用于直系子女关系。
另请注意,nth
相关的 select OR 从 1 开始,因此到 select 秒,您将使用 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>
你为什么不直接 select .answered h1
呢? :) 您的 selector 将无法工作,因为它们处于不同的 parents.