:最后一个孩子的作品,:第一个孩子没有

Eri*_*oss 5 html css html5 css-selectors

我有aside两个<div class="sku">元素.我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)

CSS

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

.sku:last-child { 
  display:none !important; /*does hide the first child*/
}
Run Code Online (Sandbox Code Playgroud)

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

Sal*_*n A 10

你不能使用:first-childpsuedo类,因为.sku它不是第一个孩子.更好的选择是使用:first-of-type(对于第一个孩子)或:nth-of-type(可以接受数字或等式)伪类:

.sku:nth-of-type(1) {
    display: none;
}
Run Code Online (Sandbox Code Playgroud)

更新了演示