creamcheese
creamcheese

Reputation: 2544

Selecting an adjacent's child... how?

trying to select an adjacent's child element with CSS... not really sure how to This is the HTML structure

<ul>
    <li>
        <a href="#">
            <span class="icon"></span>
            First level
        </a>
        <ul>
            <li>
                <a href="#">Second level</a>
            </li>
        </ul>
    </li>
</ul>

I want to say that there is a menu with multiple levels. When theres a UL existing within a LI then the needs to have a dropdown/expand icon... so I thought if I use the adjacent selector I can determine if this level has kids to expand and this is what I thought would work but didn't:

ul li a ~ ul .icon {
    // doesnt work
}
ul li a .icon ~ ul {
    // doesnt work
}

This works but I need to target the .icon

ul li a ~ ul {
    // works
} 

Cheers, Dom

Upvotes: 1

Views: 353

Answers (2)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

Building upon my comment on your question. If you have control over how the HTML for the menu is generated, a workaround would be to add an extra class to each li-element that has a sub-menu. Like this:

<ul>
    <li class="has-submenu">
        <a href="#">
            <span class="icon"></span>
            First level
        </a>
        <ul>
            <li>
                <a href="#">Second level</a>
            </li>
        </ul>
    </li>
</ul>

Then you could use a selector like this:

.has-submenu .icon {
    /* Do your stuff here */
}

Upvotes: 1

Rob
Rob

Reputation: 15160

ul is a child of li, not the anchor. So ul li ul .
If you want to select it as a sibling, then ul li a + ul

Upvotes: 0

Related Questions