为什么不是nth-of-type工作?

lon*_*556 6 html css css-selectors

我有以下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>
Run Code Online (Sandbox Code Playgroud)

我正在拼命尝试h1使用类"user-show-tab-title"(带有"答案"的类)来选择和设置第二个元素,但由于某种原因.user-show-tab-title:nth-of-type(1)选择它们并且.user-show-tab-title:nth-of-type(2)不选择任何内容.

是什么赋予了?

Jua*_*des 6

那是因为它们都是h1div中的第一个类型.nth-of-type仅适用于直接的儿童关系.

另请注意,nth相关选择器从1开始,因此要选择第二个,您将使用2,而不是1.

我不知道你的实际HTML,但是对于你拥有的,你可以使用

.answered .user-show-tab-title
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用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;
}
Run Code Online (Sandbox Code Playgroud)
    <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>
Run Code Online (Sandbox Code Playgroud)