:last-child适用,:first-child不适用

5
我有一个带有两个 <div class="sku"> 元素的 aside。我试图使用CSS操纵 :first-child,但它不起作用。然而,尝试访问 :last-child 时确实起作用。 JSFiddle HTML
<aside>
  <h1>Product Name</h1>
  <div class="sku">
    <h3>
      100 – Small
    </h3>
    <div class="dimension">
      <ul>
        <li>
          <span class="title">
            Product Dimensions
          </span>
          <span class="specs">
            23.75w
            x
            17.75h
            x
            28d
          </span>
        </li>
      </ul>
    </div>
  </div>
  <div class="sku">
    <h3>
      200 – Large
    </h3>
    <div class="dimension">
      <ul>
        <li>
          <span class="title">
            Product Dimensions
          </span>
          <span class="specs">
            29.75w
            x
            17.75h
            x
            28d
          </span>
        </li>
      </ul>
    </div>
  </div>
</aside>

CSS

.sku:first-child { 
  display:none !important; /*doesn't hide the first child*/
}

.sku:last-child { 
  display:none !important; /*does hide the first child*/
}

为什么:first-child不能选择第一个div?

1
请分享您的代码以及您想要实现的目标。如果没有更多信息,仅告诉我们某些东西不起作用是没有帮助的。 - Robbert
4
这是因为.sku不是aside元素的第一个子元素。CSS伪类(如:first-child:last-childnth-child()等)会查找父元素的子元素树以匹配正确的子元素,而不是元素.类的组合。 - Hashem Qolami
dev.sku 不是第一个子元素,h3 是。请尝试使用 :first-of-type - wolfemm
2个回答

12

由于.sku不是第一个子元素,因此您无法使用:first-child伪类。更好的选择是使用:first-of-type(用于第一个子元素)或:nth-of-type(可以接受数字或方程式的伪类):

.sku:nth-of-type(1) {
    display: none;
}

更新的演示


2

:first-child 意味着第一个子元素。在这种情况下,它是 H1,所以这不起作用。你可以使用:

h1 + .sku { }

但仅当您按照此顺序放置HTML时才生效。

那么为什么:last-child会起作用呢? - Eric Norcross
因为 .sky 是父元素的最后一个子元素。在该级别上有 3 个元素,h1 + .sku + .sku,其中 :last-child 是最后一个 sku。如果在最后一个 sku 后面有一个 h2。它不起作用。 - Niels
1
由于 CSS 伪类中没有一个是关于类名本身的,所以我会选择使用这个相邻兄弟选择器,即使在 IE7 中也支持。 - Hashem Qolami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接