How to select the first li element with CSS?
I am trying to select the first anchor tree tag of a sub menu:
<div class="footermenu"> <ul class="menu"> <li class="expanded first"> <a href="link.html">First menupoint</a> <ul class="menu"> <li class="first"><a href="#">First submenupoint</a></li> <li><a href="#">Second submenupoint</a></li> <li><a href="#">Third submenupoint</a></li> <li class="last"><a href="#">Fourth submenupoint</a></li> </ul> </li> <li class="expanded last"> <a href="link.html">Second menupoint</a> <ul class="menu"> <li class="first"><a href="#">First submenupoint</a></li> <li><a href="#">Second submenupoint</a></li> <li><a href="#">Third submenupoint</a></li> <li class="last"><a href="#">Fourth submenupoint</a></li> </ul> </li> </ul> What I'm trying to accomplish is to select only the first anchor tag of the main menupoints.
My css:
div.footermenu li.expanded a:first-child { font-weight: bold; } The problem is that this CSS still selects the submenu, and I don't know why.
+4
2 answers
You want to use div.footermenu li.expanded > a:first-child
jsFiddle
div.footermenu li.expanded > a:first-child { font-weight: bold; } In the source selector, select all the anchor elements that are the first children of li.expanded by adding a direct descendant selector, > , you indicate that you want to select only the first, direct descendant of li.expanded , which are anchors.
+9
Try the following:
<html> <head> <style TYPE="text/css"> div.footermenu li.expanded>a{ font-weight: bold; background: Red; } </style> </head> <body> <div class="footermenu"> <ul class="menu"> <li class="expanded first"> <a href="link.html">First menupoint</a> <ul class="menu"> <li class="first"><a href="#">First submenupoint</a></li> <li><a href="#">Second submenupoint</a></li> <li><a href="#">Third submenupoint</a></li> <li class="last"><a href="#">Fourth submenupoint</a></li> </ul> </li> <li class="expanded last"> <a href="link.html">Second menupoint</a> <ul class="menu"> <li class="first"><a href="#">First submenupoint</a></li> <li><a href="#">Second submenupoint</a></li> <li><a href="#">Third submenupoint</a></li> <li class="last"><a href="#">Fourth submenupoint</a></li> </ul> </li> </ul> </div> </body> </html> +4