CSS-在 id 中选择类的语法

通过类名在 id 中选择标记的选择器语法是什么?例如,我需要在下面选择什么才能使内部的“ li”变成红色?

<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>
170738 次浏览
.navigationLevel2 li { color: #aa0000 }
#navigation .navigationLevel2 li
{
color: #f00;
}

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>

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

Just needed to drill down to the last li.

    #navigation li .navigationLevel2 li

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.