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

3

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!

Commiserate answered 17/1, 2014 at 16:19 Comment(6)
You need JS/Jquery to do this...or maully add a class to the parent liShowmanship
No. CSS has no contains child selector.Pruinose
maybe use a before selector instead of an after one?Standish
@BrianGlaz how will that help?Pruinose
what does your HTML for the menu look like?Standish
The space in content: ' ▾'; isn't doing you any good. Use the margin or padding css properties if you want cross-browser whitespace.Injure
P
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

Pruinose answered 17/1, 2014 at 16:22 Comment(2)
Nice! I prefer the ▸ char on float: right; though. And you might want \25B8 to escape it in CSS.Deen
good but this arrow is not showing in my android device browser (chrome). Why is is so? Any suggestion?Valladares
B
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>
Brightman answered 22/1, 2016 at 10:36 Comment(0)
C
0

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

Cupp answered 27/11, 2019 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.