Picnic Website Code Tutorials

How Pseudo Class Selectors Select Their Element To Target

3/01/2013

Such as...

  1. :first-child
  2. :last-child
  3. :nth-child(N)
  4. :nth-of-type(N)
  5. :first-of-type
  6. :last-of-type
  7. :nth-last-of-type(N)
  8. :nth-last-child(N)
  9. :only-of-type

OMG. I just wasted an hour staring at my screen with my eyes 6 inches from the screen saying to myself - p opened - p closed - div opened - div closed - looking for the error. I was adding a div to my page and it fubared some margins. Finally I found it. It was this...

#main .column:nth-of-type(3) {
margin-right:0;
}
		

Apparently that does not mean class .column :nth-of-type. It means div :nth-of-type (given that the .column class is on a div of course). I assumed it would only target the class. It does not - it targets the 3rd div. Maybe you already knew this. I did not until now.

HOWEVER, as I later learned, it's not quite that simple.

When you say .column:nth-of type(3) then the browser will first check what element has the class of .column applied (there may be more than one type of element to take note of). If .column is applied to a div element for example then the browser will count from that the first div element (regardless of its class) and find the third div element in sequence but will only apply the rule if that third element in sequence has a class of .column. It does not look for three .column classes but looks from the first div element and then finds the third of that type but only applies the rule if that third of type has the class.

.column:nth-of-type(3) { background:red; }
		
<div class="column"></div>
<div></div>
<div></div>
<div class="column"></div>
<div class="column"></div>
		

Nothing in the above will get targeted because the third div in sequence doesn't have a class of column. However...

.column:nth-of-type(3) { background:red; }
		
<div class="column"></div>
<div></div>
<div class="column"></div>
<div class="column"></div>
<div class="column"></div>
		

In the above the third div will have a background of red but note that it is only the second instance of the .column class. So to recap the browsers first checks what element the class belongs to and then it finds the third of that element. If that third element doesn't have the same class then no match is made. There could also be other element intermingled in the above with a class of column and they would get selected on the same basis as above and each treated separately.

So... the browser looks at .column as sees that its applied to a div. It then counts from the first div in that section (regardless of its class) and then finds the third div. If that third div doesn't have a class of .column then no match is made.

Need help adding this or other code to your website? Post it here in the forum! Forum

Sponsors

Top Donators

Friends of Mine