Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

pseudo-classes selectors : first-child

Hello, i'm wondering why we write li:first-child and not ul:first-child to target the first li of the list ...? li has no child but is a child of ul, isn't it ? Thanks !

4 Answers

Tom Mertz
Tom Mertz
15,254 Points

Hi,

When you use the the li:first-child selector you aren't saying, "Look for the first child of the li element" (Which had me confused for a long time)

What you are actually saying instead is, "Find everything single li element that IS a first child.

It's like this because it lets you get the specific element (in this case li) that you want. Imagine that you had code like

<ul>
<p>Hi I'm a first child</p>
</ul>

<ul>
<li>I'm a first child too!</li>
</ul>

(Not that you'd ever do this but for other elements you might - this is an example.)

If you wanted all the li elements that were first-children, but had to use ul:first-child, what would you get when you did ul:first-child?

Yup, you'd get the paragraph AND the li element because they are both first children of ul. Instead, CSS makes you choose which first-child you are grabbing. So you can get the paragraph using p:first-child or the list item using li:first-child.

Hope this helps!

Kevin Korte
Kevin Korte
28,149 Points

You're question is valid. In my head I just always phrase it as I want to select a list item, that is the first child. CSS3 is smart enough to find the first child that IS that element you are selecting.

If you called first child on the unordered list instead, those changes would apply to all of the list items as well, first child or not.

I'm a visual person, does this help? http://codepen.io/kevink/pen/kxDgG

ok thanks (it's still a bit confused, but I understand)

"When you use the the li:first-child selector you aren't saying, "Look for the first child of the li element" (Which had me confused for a long time)

What you are actually saying instead is, "Find everything single li element that IS a first child."

Aaaaa ok ! Now I understand. thank you ;)