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
Gard Mikael Fjeldavli
19,416 PointsFirst child
I have a menu in my site with the id="dd_menu_2" where I want to change styles only to the first element.
I thought this was achieved by typing
#dd_menu_2 ul li:first-child {
color: tomato;
}
But this affects all the list items in the unordered list. When I inspect the element in my browser(chrome) I see that the style is applied to to the first child, but it also overrides the style of all the other list items.
This is the html of the menu
<div class="dropdownmenu dd_prof" id="dd_menu_2">
<ul class="drop_down_ul">
<li><?php echo $user_name; ?></li>
<a href="../settings.php"><li>Settings</li></a>
<a href="logout.php"><li>Logout</li></a>
</ul>
</div>
Why? And how can I fix it?
2 Answers
Scott Evans
4,236 PointsHi Gard!
The reason this is happening is because the pseudo element selected css:first-child is applied to any element that is the first child of any parent element. As you can see below, i have added comments to your HTML code to help you understand what is going on.
<div class="dropdownmenu dd_prof" id="dd_menu_2">
<ul class="drop_down_ul">
<!-- The LI element below is the first-child of the UL with the id "drop_down_ul -->
<li><?php echo $user_name; ?></li>
<!-- What i believe you're missing is the fact that both of the LI elements bellow are technically still first-child elements of the <a> tags -->
<a href="../settings.php"><li>Settings</li></a>
<a href="logout.php"><li>Logout</li></a>
</ul>
</div>
There are 2 ways to fix this, you could either specify a class or id on the first element in your UL or you could use this selector
#dd_menu_2 ul > li:first-child {
color: tomato;
}
Using the > specifies that you want to search for only direct descendants of the UL.
Give it a go and let know how you get on. Good Luck, Scott.
Gard Mikael Fjeldavli
19,416 PointsThanks a bunch. That completely answered my question! =)
Scott Evans
4,236 PointsScott Evans
4,236 PointsI take it it went well, good good :D