Nesting child selectors in CSS
Asked Answered
K

1

8

I have this HTML:

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

I want to apply CSS only to item "Foo." I do not want to tag every top-level <li> with a special class. 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. 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?

Karisa answered 15/6, 2014 at 5:22 Comment(2)
try .navbar ul > li:first-child . just guessing here.Epstein
The problem is that the style applies to the entire <li> (text-transform cascades), and the "child" <li> is part of parent.Spectrogram
I
9

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.

The problem is not with the selector; it's the fact that text-transform, like most text properties, is inherited by default. So even though you're applying the style only to immediate li elements, the nested ones receive it by inheritance.

You will need to reverse this manually on the nested elements:

.navbar > ul > li li {
    text-transform: none;
}
Isabel answered 15/6, 2014 at 5:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.