CSS 向只有子菜单的菜单项添加下拉箭头指示符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21190694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add dropdown arrow indicators to menu items that have submenus only?
提问by user3101431
I am currently trying to add arrow indicators on my navigation menu for items which have submenu options.
我目前正在尝试在导航菜单上为具有子菜单选项的项目添加箭头指示器。
Currently I am using this CSS:
目前我正在使用这个 CSS:
.mainNav li > a:after {
color: #444;
content: ' ?';
}
But this adds a dropdown arrow to every <li>
regardless of if there is a submenu or not. Is there a way with just CSS to only add this arrow to items that have sub-items?
但这会为每个添加一个下拉箭头,<li>
无论是否有子菜单。有没有办法只用 CSS 只将此箭头添加到具有子项目的项目?
Thanks!
谢谢!
回答by BenM
No. CSS has no contains child
selector. You'd probably be better to just add a class to the li
element. For example:
不。CSS 没有contains child
选择器。您可能最好只向li
元素添加一个类。例如:
<li class="has-child">
<a href="#">The Link</a>
<ul class="child">
<li>Child 1</li>
</ul>
</li>
Your CSS selector would in turn look like:
您的 CSS 选择器将如下所示:
.mainNav li.has-child > a:after {
color: #444;
content: ' ?';
}
You could have jQuery add the class for you, if that's an option:
如果这是一个选项,您可以让 jQuery 为您添加类:
$('.mainNav li:has(ul)').addClass('has-child');
回答by dmpost
CSS has no contains child
selector.
However it has various sibling
selectors, only-child
and not(:only-child)
Since you add indicator to the anchor, use following CSS
CSS 没有contains child
选择器。但是它有各种sibling
选择器,only-child
并且not(:only-child)
由于您向锚点添加了指示器,因此请使用以下 CSS
.mainNav li>a:not(:only-child):after {
color: #444;
content: ' ?';
}
<div class="mainNav">
<li>
<a href="#">The item with child</a>
<ul class="child">
<li>Child 1</li>
</ul>
</li>
<li>
<a href="#">No child item</a>
</li>
</div>
回答by Steef
Yes you can without any jQuery : https://css-tricks.com/targetting-menu-elements-submenus-navigation-bar/
是的,你可以不用任何 jQuery:https: //css-tricks.com/targetting-menu-elements-submenus-navigation-bar/