简体   繁体   English

在CSS中嵌套子选择器

[英]Nesting child selectors in CSS

I have this HTML: 我有这个HTML:

<div class="navbar">
    <ul>
        <li>Foo
            <ul>
                <li>Bar</li>
            </ul>
        </li>
    </ul>
</div>

I want to apply CSS only to item "Foo." 我想只将CSS应用于项目“Foo”。 I do not want to tag every top-level <li> with a special class. 我不想用特殊的类标记每个顶级<li>。 My limited knowledge tells me I should be able to do this: 我有限的知识告诉我,我应该能够做到这一点:

.navbar > ul > li  {
    text-transform: uppercase;
}

But the style gets applied to "Bar" as well when I do it like this. 但是当我像这样做时,风格也应用于“Bar”。 I thought that '>' specifies only immediate children, does it not work the same way when it's nested? 我认为'>'只指定了直接的孩子,当它嵌套时它是不是以同样的方式工作? Is what I'm trying to do even possible? 我正在努力做甚么可能吗?

I thought that '>' specifies only immediate children, does it not work the same way when it's nested? 我认为'>'只指定了直接的孩子,当它嵌套时它是不是以同样的方式工作?

It does work the same way. 它确实以同样的方式工作。 Since you're anchoring the ul directly to .navbar with .navbar > ul , your selector does apply to li elements directly that particular ul only. 由于您使用.navbar > ulul直接锚定到.navbar.navbar > ul您的选择器仅直接应用于特定ul li元素。

The problem is not with the selector; 问题不在于选择器; it's the fact that text-transform , like most text properties, is inherited by default . 事实上, text-transform与大多数文本属性一样,默认是继承的 So even though you're applying the style only to immediate li elements, the nested ones receive it by inheritance. 因此,即使您只将样式应用于直接li元素,嵌套的元素也会通过继承接收它。

You will need to reverse this manually on the nested elements: 您需要在嵌套元素上手动反转:

.navbar > ul > li li {
    text-transform: none;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM