Here's a code of the simpliest multilevel menu:
<nav>
<ul>
<li><a href="#">I am a 1st level link</a></li>
<li><a href="#">I am a 1st level link with children and I want to have an arrow next to me (or different background)</a>
<ul>
<li><a href="#">I am a 2nd level link</a></li>
<li><a href="#">I am a 2nd level link with children and I want to have an arrow next to me (or different background)</a>
<ul>
<li><a href="#">I am a 3nd level link</a></li>
<li><a href="#">I am a 3nd level link</a></li>
</ul>
</li>
<li><a href="#">I am a 2nd level link</a></li>
</ul>
</li>
<li><a href="#">I am a 1st level link</a></li>
<li><a href="#">I am a 1st level link</a></li>
</ul>
</nav>
Is there a way of selecting links with children and adding them different styling (background, list-style-type icons etc.)? The menu is dynamic so giving ids or classes won't help in this case.
I'd love to see it in CSS3, if not possible - jQuery or PHP would be ok. I want it to be cross-browser ready. But at the moment don't even know WHERE to start?
Thanks a lot!
The :only-child
pseudoselector selects elements which are the only child of their parent. You can use this in CSS3 to style elements without arrows, overriding those with arrows. You can use e.g. the :first-of-type
pseudoselector for the main selector in an attempt to prevent browsers which do not support :only-child
from displaying the arrows on all elements.
For example:
nav ul a:first-of-type {
/* :first-of-type for CSS3-incompat browsers; can be safely removed */
/* Apply arrow code */
background: ...;
}
nav ul a:only-child {
/* Undo arrow code above */
background: transparent;
}
This might get you going:
$('li>a')
.filter(function(){
return $(this).next().is('ul') ? true : false;
}).addClass('haveChild');
This seems to work using jquery... you can customize the special class to be a background image with an error or whatever you want....
<script>
$(document).ready(function(){
$('ul a + ul').each(function(){
$(this).prev().addClass('special');
});
});
</script>
<style type="text/css">
.special {background-color: red;}
</style>
I used the code provided above and created an example using jsFiddle.
View example here