CSS child selector

I understand the difference between a child and descendants is just fine. However, I have a problem with the selector. Perhaps I misunderstand something. Take the following HTML as an example. This is a 3 level navigation menu.

<div id="nav">
    <ul class="menu">
        <li><a href="#">Menu Item 1</a></li>
        <li><a href="#">Menu Item 2</a>
            <ul class="sub-menu">
                <li><a href="#">Sub Menu Item 1</a></li>
                <li><a href="#">Sub Menu Item 2</a>
                    <ul class="sub-menu">
                        <li><a href="#">Sub Sub Menu Item 1</a></li>
                        <li><a href="#">Sub Sub Menu Item 2</a></li>
                        <li><a href="#">Sub Sub Menu Item 3</a></li>
                    </ul>
                </li>
                <li><a href="#">Sub Menu Item 3</a></li>
            </ul>
        </li>
        <li><a href="#">Menu Item 3</a></li>
    </ul>
</div>

Based on my understanding of the child (>) selector in css, the following would be true:

#nav {}
#nav ul.menu {}
#nav ul.menu > li {} /* main navigation items only */
#nav ul.menu > li > ul.sub-menu li {} /* the 2nd tier only */
#nav ul.menu > li > ul.sub-menu ul.sub-menu {} /* the 3rd tier only */

However, this does not seem to be the case. Css for tier 2 also applies to tier 3. And only with the declaration !importantI can rewrite the 2nd level in the last css definition.

Make sense?

+3
source share
3 answers
nav ul.menu > li {} /* main navigation items only */

correctly

#nav ul.menu > li > ul.sub-menu li {} /* the 2nd tier only */

wrong . You select a child ul.menu lithat has a child ul.sub-menu, all the elements libelow it.

, :

#nav ul.menu > li > ul.sub-menu > li {}

#nav ul.menu > li > ul.sub-menu ul.sub-menu {} 

, 3 .

+5
#nav ul.menu > li > ul.sub-menu li {}

2 .

#nav > ul.menu > li > ul.sub-menu > li {}

2- ...

+1

#nav ul.menu > li > ul.sub-menu li {}//

The last selector ul.sub-menu liselects both children lifrom the 2nd level and decendant liwithin the 3rd level.

#nav ul.menu > li > ul.sub-menu > li {}// can force it to limit the second level

Furthermore, according to http://www.evotech.net/blog/2008/05/browser-css-selector-support/ , support for the 'E> F' selectors distorts IE6 a bit, which may not be a problem for you.

+1
source

All Articles