第一类和儿童

Igo*_*zlo 1 css css-selectors css3

我开始被混淆>,:nth-child():nth-of-type().

我有 :

<div class="entry-content">
    <div class="first-img">
        <img />
    </div>
    <div class="first-box">
        <blockquote></blockquote>
    </div>
    <blockquote></blockquote>
</div>
Run Code Online (Sandbox Code Playgroud)

我想设置第一个blockquote直接在其中的样式.entry-content(这意味着这是blockquote示例中的第二个)但不是第一个blockquote在div中.first-box.

我试过了.entry-content > blockquote:nth-child(2),.entry-content:nth-of-type(2)他们也不行.

是否.entry-content > blockquote意味着:

  • 我选择仅直接在条目内容中的块引用,或者
  • 所有直接在条目内容中的块引用(不在其他div中)以及在div中的那些?

Har*_*rry 6

您实际需要使用的选择器是:

.entry-content > blockquote:nth-of-type(1) {
  /* styles */
}
Run Code Online (Sandbox Code Playgroud)

所有:nth-*,*-child选择对谁都有一个共同的父元素才能正常工作.在问题中提供的HTML中,blockquote直接在其下面的HTML是.entry-content其类型的第一个,因此您应该使用nth-of-type(1)它来代替它nth-of-type(2).

.entry-content > blockquote:nth-of-type(1) {
  background: red;
}
Run Code Online (Sandbox Code Playgroud)
<div class="entry-content">
  <div class="first-img">
    <img />
  </div>
  <div class="first-box">
    <blockquote>Descendant</blockquote>
  </div>
  <blockquote>Child</blockquote>
</div>
Run Code Online (Sandbox Code Playgroud)


现在解释其他选择器(要么没有工作,要么没有尝试):

  • .entry-content > blockquote:nth-child(2)- 如果它恰好是第二个孩子blockquote,这将选择直接存在于元素下的元素class='entry-content'.这里有两个div子元素blockquote,因此blockquotenth-child(3).
  • .entry-content > blockquote:nth-of-type(2)- 只有一个类型blockquote的元素直接在元素下面class='entry-content',因此它不会选择任何内容.
  • .entry-content > blockquote- 这将选择blockquote直接出现在元素下的所有元素,class='entry-content'因此不会选择元素下面的元素class='first-box.这是因为>是子选择器并且仅选择直接存在于引用元素下的元素.
  • .entry-content blockquote- 这与上面的非常相似,但由于>缺少它实际上选择所有blockquote元素作为元素的后代,class='entry-content因此它将选择blockquote所提供的HTML中存在的元素.
  • .entry-content:nth-of-type(2) - 问题中提供的这个选择器与其他选择器相比是一个不同的选择器.如果它也有,则选择每种类型的第二个元素(在共同父项下)class='.entry-content.