Add dropdown arrow indicators to menu items that have submenus only?

user3101431 picture user3101431 · Jan 17, 2014 · Viewed 43.4k times · Source

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!

Answer

BenM picture BenM · Jan 17, 2014

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