Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style the first and last li with CSS or jQuery?

Tags:

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> 
like image 869
user520300 Avatar asked Jan 17 '12 15:01

user520300


People also ask

How do you style the first Li in CSS?

If you'd like to use jQuery you could use the following: $('#nav > ul li'). first(). css('background-color', 'red'); $('#nav > ul li').

How do I select the first and last child in CSS?

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.

Which selector will add the style to first list of UL?

CSS :first-child Selector.


1 Answers

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.

like image 125
Explosion Pills Avatar answered Sep 19 '22 19:09

Explosion Pills