8

I am currently trying to add arrow indicators on my navigation menu for items which have submenu options.

Currently I am using this 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?

Thanks!

user3101431
  • 407
  • 2
  • 8
  • 15

3 Answers3

14

No. CSS has no contains child selector. You'd probably be better to just add a class to the li element. For example:

<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:

.mainNav li.has-child > a:after {
   color: #444;
   content: ' ▾';
}

You could have jQuery add the class for you, if that's an option:

$('.mainNav li:has(ul)').addClass('has-child');

jsFiddle Demo

BenM
  • 52,573
  • 26
  • 113
  • 168
  • Nice! I prefer the ▸ char on `float: right;` though. And you might want \25B8 to escape it in CSS. – Domino Feb 17 '15 at 19:19
  • good but this arrow is not showing in my android device browser (chrome). Why is is so? Any suggestion? – Umar Asghar May 04 '16 at 12:59
4

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

 .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>
dmpost
  • 96
  • 5
0

Yes you can without any jQuery : https://css-tricks.com/targetting-menu-elements-submenus-navigation-bar/

Steef
  • 569
  • 5
  • 21