Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:last-child works, :first-child doesn't [duplicate]

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?

like image 901
Eric Norcross Avatar asked Aug 22 '14 19:08

Eric Norcross


2 Answers

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

like image 102
Salman A Avatar answered Sep 21 '22 20:09

Salman A


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.

like image 31
Niels Avatar answered Sep 18 '22 20:09

Niels