Alex Rivera | Logout

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

Asked 2012-01-17T15:07:19.383
26

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>
Edit
Report

1 Answer

37

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.

answered 2012-01-17T15:09:18.333

Your Answer