【问题标题】::last-child works, :first-child doesn't [duplicate]:last-child 有效, :first-child 无效
【发布时间】:2014-10-16 18:08:03
【问题描述】:

我有一个带有两个 <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?

【问题讨论】:

  • 请分享您的代码以及您想要完成的工作。如果没有更多信息,告诉我们某些事情不起作用是没有帮助的。
  • 这是因为.sku 不是aside 元素的第一个 子元素。 CSS 伪类,例如 :first-child:last-childnth-child()、...查看父级的子树以匹配正确的子元素,而不是 element.class 的组合。
  • dev.sku 不是第一个孩子——h3 是。请改用:first-of-type

标签: css html css-selectors


【解决方案1】:

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

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

Updated Demo

【讨论】:

    【解决方案2】:

    :first-child 表示第一个孩子。在这种情况下是H1。所以这不起作用。您可以使用:

    h1 + .sku { }
    

    但前提是这是您放置 HTML 的顺序。

    【讨论】:

    • 那么为什么 :last-child 工作呢?
    • 因为 .sky 是父元素的最后一个子元素。您在该级别上有 3 个元素,h1 + .sku + .sku 其中 :last-child 是最后一个 sku。如果您在最后一个 sku 之后有一个 h2。它不起作用。
    • @greetification 由于没有一个 CSS 伪类尊重类名本身,我会选择这个即使在 IE7 中也支持的相邻兄弟选择器。
    猜你喜欢
    • 2013-03-03
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2011-12-17
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多