CSS - 在 id 中选择类的语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1140646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:50:04  来源:igfitidea点击:

CSS - Syntax to select a class within an id

csscss-selectors

提问by Jeremy

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?

通过类名在 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>

回答by John Sheehan

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

回答by Andy Ford

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:

如果您有第三级 LI,您可能需要重置/覆盖它们将从上述选择器继承的一些样式。您可以像这样定位第三级:

#navigation li li li {}

回答by Galen

.navigationLevel2 li { color: #aa0000 }

回答by Jason

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

这里有两个选项。我更喜欢 navigationAlt 选项,因为它最终涉及的工作较少:

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

回答by kkrobbins

Just needed to drill down to the last li.

只需要深入到最后一里。

    #navigation li .navigationLevel2 li