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


#1


https://www.codecademy.com/en/courses/web-beginner-en-WF0CF/3/5?curriculum_id=50579fb998b470000202dc8b

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

<!DOCTYPE html>
<html>
	<head>
		<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
		<title>Result</title>
	</head>
	<body>
		<!--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/>
	</body>
</html>

/*Add your CSS below!*/
a:hover {
    text-decoration:none;
}
a:first-child {
    color:#cdbe70;
}
a:nth-child(3) {
    color:#ffC125;
}


#2

nth-child count all elements, so first element:

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

second child:

<br/>

third child:

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

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


#3

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>.


#4

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

<h1>heading</h1>
<p>paragraph</p>

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


#5

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.


#6

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


#7

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.


#8

because if you do:

p:nth-child(3)

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


#9

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.