CSS - Syntax to select a class within an id

CssCss Selectors

Css Problem Overview


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>

Css Solutions


Solution 1 - Css

#navigation .navigationLevel2 li
{
    color: #f00;
}

Solution 2 - Css

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 {}

Solution 3 - Css

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>

Solution 4 - Css

.navigationLevel2 li { color: #aa0000 }

Solution 5 - Css

Just needed to drill down to the last li.

    #navigation li .navigationLevel2 li

Solution 6 - Css

Note also that you can select the LI that's a direct child of the given id using the > selector (called child selector):

#navigation>li
{
    color: blue;
}

and therefore the deeper nested one

#navigation>li>ul>li
{
    color: red;
}

without the need of the additonal css class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremyView Question on Stackoverflow
Solution 1 - CssJohn SheehanView Answer on Stackoverflow
Solution 2 - CssAndy FordView Answer on Stackoverflow
Solution 3 - CssJasonView Answer on Stackoverflow
Solution 4 - CssGalenView Answer on Stackoverflow
Solution 5 - CsskkrobbinsView Answer on Stackoverflow
Solution 6 - Cssnot2savvyView Answer on Stackoverflow