Reputation: 4479
I have the following 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>
I'm desperately trying to select and style the 2nd h1
element with the class "user-show-tab-title" (the one with "answers")
but for some reason .user-show-tab-title:nth-of-type(1)
selects them both and .user-show-tab-title:nth-of-type(2)
doesn't select anything.
What gives?
Upvotes: 8
Views: 8284
Reputation: 92274
That's because they are both the first of type h1
within a div. nth-of-type
applies only to immediate child relationship.
Also note that the nth
related selectors start at 1, so to select the second you would use 2, not 1.
I don't know your actual HTML, but for what you have, you can just use
.answered .user-show-tab-title
If you really want to use nth-of-type
, here's how you can use it. I'm inserting some dummy <p>
s otherwise, all the children of <section>
would be of the same type.
.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>
Upvotes: 9
Reputation: 23
Why don't you just select .answered h1
instead? :) your selector won't work because they are under different parents.
Upvotes: 2