How can I style the first (top level) li
and the last (top level) li
with CSS or jQuery?
I am using CSS to set the first li
style but it is also styling the first li
in each secondary level ul
, so how can I get it to style only the li
with Main 1 in it and the last one with Main 6 in it?
Here is my code:
<style> ul li:first-child { width: 800px; border:1px solid #fc5604; border-top-width:thin; (2px) } </style>
and HTML:
<div id="nav"> <ul> <li><a href="#">Main 1</a> <ul> <li><a href="#">Sub 1a</a></li> <li><a href="#">Sub 1b</a></li> <li><a href="#">Sub 1c</a></li> </ul> </li> <li><a href="#">Main 2</a> <ul> <li><a href="#">Sub 2</a></li> </ul> </li> <li><a href="#">Main 3</a> <ul> <li><a href="#">Sub 3</a></li> </ul> </li> <li><a href="#">Main 4</a> <ul> <li><a href="#">Sub 4</a></li> </ul> </li> <li><a href="#">Main 5</a></li> <li><a href="#">Main 6</a> <ul> <li><a href="#">Sub 6</a></li> </ul> </li> </ul> </div>
If you'd like to use jQuery you could use the following: $('#nav > ul li'). first(). css('background-color', 'red'); $('#nav > ul li').
Using the following pseudo classes: :first-child means "select this element if it is the first child of its parent". :last-child means "select this element if it is the last child of its parent". Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.
CSS :first-child Selector.
You have to use the immediate child selector:
ul > li:first-child
This rule will affect an <li>
that is only immediately preceded by a <ul>
. This should apply to both jQuery and css. Not all browsers can use the pseudo classes (especially last-child
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With