5

I have an aside with two <div class="sku"> elements. I'm trying to use CSS to manipulate the :first-child but it doesn't work. However, when trying to access the :last-child it does.

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*/
}

Why won't :first-child select the first div?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Eric Norcross
  • 4,177
  • 4
  • 28
  • 53
  • 1
    Please share your code and what you are trying to accomplish. Telling us something isn't working isn't helpful without more information. – Robbert Aug 22 '14 at 19:51
  • 4
    This is because `.sku` is not the **first** child of the `aside` element. CSS pseudo-classes such as `:first-child`, `:last-child`, `nth-child()`,... look through the children tree of the parent to match the proper child element, not a combination of `element.class`. – Hashem Qolami Aug 22 '14 at 19:51
  • `dev.sku` isn't the first child — `h3` is. Try `:first-of-type` instead. – wolfemm Aug 22 '14 at 19:52

2 Answers2

12

You cannot use :first-child psuedo class since .sku is not the first child. A better option is to use either :first-of-type (for first child) or :nth-of-type (which can accept a number or an equation) pseudo classes:

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

Updated Demo

Salman A
  • 262,204
  • 82
  • 430
  • 521
2

The :first-child means the first child. Which is in this case the H1. So this does not work. You can use:

h1 + .sku { }

But only if this is the order you place your HTML.

Niels
  • 48,601
  • 4
  • 62
  • 81
  • So why does :last-child work then? – Eric Norcross Aug 22 '14 at 19:54
  • Because the .sky is the last child of the parent element. You have 3 elements on that level, `h1 + .sku + .sku` which :last-child is the last sku. If you had a h2 after the last sku. It doesnt work. – Niels Aug 22 '14 at 19:55
  • 1
    @greetification Since none of CSS pseudo-classes respect to class names themselves, I'd go with this adjacent sibling selector which is supported even in IE7. – Hashem Qolami Aug 22 '14 at 20:01