开发者

CSS Child Selector

开发者 https://www.devze.com 2023-03-12 05:20 出处:网络
I understand the difference between child and descendants just fine. I am having an issue with the child selector however. Perhaps I am not understanding something correctly. Take the following HTML a

I understand the difference between child and descendants just fine. I am having an issue with the child selector however. Perhaps I am not understanding something correctly. Take the following HTML as an example. This is a 3 tier 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>&l开发者_如何学Got;/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 */

This does not seem to be the case however. The css for the 2nd tier is being applied to the 3rd tier as well. And only with an !important declaration am I able to overwrite the 2nd tier within the last css definition.

Make sense?


nav ul.menu > li {} /* main navigation items only */

correct

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

wrong - You are selecting the ul.menu child li which has child ul.sub-menu, all the li elements under it.

If you want to restrict it to that level only, use this:

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

The last one

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

should work fine as long as you keep it in 3 tiers only.


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

will apply to 2 tier and beyond.

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

would apply to 2nd tier only...


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

The last ul.sub-menu li selector selects both the child li elements from the 2nd tier and the decendant li within the 3rd tier.

#nav ul.menu > li > ul.sub-menu > li {} // might force it to restrict to the second tier

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

0

精彩评论

暂无评论...
验证码 换一张
取 消