【问题标题】:How to apply css to only one level of list items (not to child elements)如何仅将 css 应用于一级列表项(不应用于子元素)
【发布时间】:2011-12-17 00:16:17
【问题描述】:

在下面的代码中,我将向下数组(通过生成的内容)添加到具有子菜单的顶级元素。我正在向具有子菜单的子菜单元素添加一个右箭头。

但是,我需要一些关于我的 css 的帮助,因为如果父母有孩子,它会将箭头应用于所有子元素。我只需要将它应用于那些有子元素的元素。

<ul id="menu-site-menu">
    <li class="hasChild top"><a href="#">About Us</a>
        <ul class="sub-menu">
            <li><a href="#">Our Charity Partners</a></li>
            <li><a href="#">Privacy Policy</a></li>
        </ul>
    </li>
    <li class="hasChild top"><a href="#">Buy Apparel</a>
        <ul class="sub-menu">
            <li class="hasChild sub"><a href="#">Benevolent Elephant</a>
                <ul class="sub-menu">
                    <li><a href="#">Benevolent Elephant Short Sleeve</a></li>
                    <li><a href="#">Benevolent Elephant Long Sleeve</a></li>
                </ul>
            </li>
            <li class="hasChild sub"><a href="#">Eagle-Spirit</a>
                <ul class="sub-menu">
                    <li><a href="#">Eagle-Spirit Short Sleeve</a></li>
                    <li><a href="#">Eagle-Spirit Long Sleeve T-Shirts</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#">Customer Service</a></li>
    <li><a href="#">Contact Us</a></li>
</ul>

下面是css

.hasChild.top a:after {
    content: ' ';
    height: 0;
    position: absolute;
    bottom:-5px;
    right:-5px;
    width:0;
    border: 5px solid transparent;
    border-top-color: #ccc;
}
.hasChild.sub a:after {
    content: ' ';
    height: 0;
    position: absolute;
    bottom:0;
    right:-5px;
    width:0;
    border: 5px solid transparent;
    border-left-color: #ccc;
}

【问题讨论】:

    标签: css


    【解决方案1】:

    添加子选择器&gt;:

    .hasChild.top > a:after { 
    } 
    .hasChild.sub > a:after { 
    } 
    

    【讨论】:

    • 需要注意的是,如果需要支持IE6,这个是不行的。
    • @DanHerbert:在 IE6 上,:after 首先将不起作用。或者几乎其他任何事情。让我们忽略它,也许它会最终消失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2013-05-30
    • 2012-08-03
    • 1970-01-01
    相关资源
    最近更新 更多