CSS Selectors Lesson Number 18


#1

I understand how to use the following:

selector:first-child {
font-family: Helvetica;
}

selector:nth-child(3) {
color: green;
}

HOWEVER, it seems that CSS fails to distinguish the order of the children when you separate them with < p >

For example:

a:first-child {
color: blue;
}

a:nth-child(3) {
color:yellow;
}

Once this is running, it seems that all the children of < a > are blue color, and the a:nth-child(3) has no effect.
Why does having the < p > affect this?


#2

I think it does this because a is the first child of each p tag. Since there is only one a tag per p tag, each a tag is it's p tags first child :slightly_smiling: .

You will need to do this to access the correct a tags

p:first-child a{
  color: red;
}
p:nth-child(3) a{
color:yellow;
}

Now you are accessing the first p tag which is unique and then accessing it's a tag.

you can even go a step further...

Say you have multiple a tags in your p tags

<p><a href="#">hi</a><a href="#">hi</a></p>
<p><a href="#">hi</a><a href="#">hi</a></p>
<p><a href="#">hi</a><a href="#">hi</a></p>

You can access the 2nd a tag of the 3rd p tag with the css selectors:

p:nth-child(3) a:nth-child(2){
  color:yellow;
}

Hope that explains it :sunny:


#3

Thanks! I realized this was the case through trial & error.


#4

Cool :smile: Glad I could help.