18. show it if you know it: nth-child(3) counting issue



Everything works, except the :nth-child(3) colors link 2 instead of 3. Can't figure out what I do wrong.

<!DOCTYPE html>
		<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
		<!--Add your HTML below!-->
		<a href="http://link.net">link 1</a><br/>
		<a href="http://link.net">link 2</a><br/>
		<a href="http://link.net">link 3</a><br/>

/*Add your CSS below!*/
a:hover {
a:first-child {
a:nth-child(3) {


nth-child count all elements, so first element:

<a href="http://link.net">link 1</a>

second child:


third child:

<a href="http://link.net">link 2</a>

so due to your breaks (<br/>), the count changes


Thanks, you're right. With :nth-child(5) it works for 'Link 3'.
I just thought that with a:nth-child() it counts the children of type <a>.


no, nth-child count all elements, but there is a catch, look at this code:


now, if i have the following css code:

p:first-child { color: red; }

nothing will color red, since the first element is h1 heading and not a paragraph. the css selector (p in this case) should be a match to the element you want to color


I see. It act's as a double condition: should be <p> AND :first-child. I also found out that in fact there is a :nth-of-type() too.

This is nice (and versatile) stuff.


yes, exactly. That was going to my next answer if you got the hang of this, there is indeed a nth-of-type


Guys, I still do not get why nth-child count all elements.
What the point of putting "a" here -> a:nth-child ?
I thought nth-child is made to count elements that belong to some parent, not everything on the page.


because if you do:


only if the third element is a paragraph (of any parent), the styling between the curly brackets gets applied. If the third element for example is a h3 heading, the styling doesn't get applied


Yes, and the a also is the selector that specifies where and on which level the counting of childs begins. If you leave the a, where does the pseudo-element connect to?

So if you use this in unordered lists with several levels it's important to specify the right level and type for the pseudo-element.