views:

1096

answers:

4

What is the selector syntax to select a tag within an id via the class name? For example, what do I need to select below in order to make the inner "li" turn red?

<html>
<head>
    <style type="text/css">
     #navigation li
     {
      color: green;
     }

     #navigation li .navigationLevel2
     {
      color: red;
     }
    </style>
</head>
<body>
    <ul id="navigation">
     <li>Level 1 item
      <ul class="navigationLevel2">
       <li>Level 2 item</li>
      </ul>
     </li>
    </ul>
</body>
</html>
+1  A: 

.navigationLevel2 li { color: #aa0000 }

Galen
IF this does the trick without applying it to unwanted li:s, then this is the way to go, since it has fewer selectors and thus is faster. At least according to Google's page performance advice.
PatrikAkerstrand
+3  A: 
#navigation .navigationLevel2 li
{
    color: #f00;
}
John Sheehan
has unneed selectors!
Galen
i meant unneeded!
Galen
Only if the example shown is all the markup. For all you know, the markup needed is more complicated. I based my answer off the information given.
John Sheehan
A: 

Here's two options. I prefer the navigationAlt option since it involves less work in the end:

<html>
<head>
    <style type="text/css">
        #navigation li
        {
                color: green;
        }

        #navigation li .navigationLevel2
        {
                color: red;
        }
        #navigationAlt
        {
                color: green;
        }
        #navigationAlt ul
        {
                color: red;
        }
    </style>
</head>
<body>
    <ul id="navigation">
        <li>Level 1 item
                <ul>
                        <li class="navigationLevel2">Level 2 item</li>
                </ul>
        </li>
    </ul>
    <ul id="navigationAlt">
        <li>Level 1 item
                <ul>
                        <li>Level 2 item</li>
                </ul>
        </li>
    </ul>
</body>
</html>
Jason
+3  A: 

This will also work and you don't need the extra class:

#navigation li li {}

If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:

#navigation li li li {}
Andy Ford