Applying Style to last li in a ul with CSS / Jquery

37,268

Solution 1

Why do you have a <div> inside the <li>? Completely possible without that.

Anyways, this is how to do it with jQuery:

$('ul > li:last-child > div').css('border-bottom','1px solid black');

Solution 2

:last-child is CSS3, unlike :first-child which was introduced in CSS2, and has no IE support while. I believe the following is the safest way to implement it using jquery

$('li').last().addClass('someClass');

Solution 3

Here's a CSS only solution:

Apply the bottom border to the ul. To make it work cross-browser, remove the padding from the ul and bump the list over with a margin.

ul.border {border-bottom:1px solid #000;padding:0;margin-left:40px;}
ul.border li {border-top:1px solid #000;}

<ul class="border">
   <li>Some content</li>
   <li>some more content</li>
   <li>final content</li>
</ul>

Solution 4

:last-child doesn't work in IE7 (not sure on IE8), so you'll have to do the jQuery route. Your css lines up pretty much the same way the selectors would work in jQuery:

$('ul > li:last > div').addClass('someclass');

Solution 5

I am not sure why do you need the "<div>" inside the "<li>" but if you don't need it you could simply use:

ul > li:last-child {

I tested it and work for me in chrome, ie8, firefox and safari.

Share:
37,268
JoshBerke
Author by

JoshBerke

Developing with Microsoft Technologies for over 18 years.

Updated on August 01, 2020

Comments

  • JoshBerke
    JoshBerke almost 4 years

    Given the following HTML:

    <ul>
       <li><div>Some content</div></li>
       <li><div>some more content</div></li>
       <li><div>final content</div></li>
    </ul>
    

    I would like to apply a top border around each div. On the last div I would like to put a bottom border. I am targeting IE7/8. I have the top border working fine, I need help getting the bottom border.

    I've tried:

       ul > li:last-child > div
        {
            border-bottom: solid 1px black;
        }
    

    I've also tried using last-type-of.

    I am looking for a CSS solution and a Jquery solution

  • JoshBerke
    JoshBerke almost 15 years
    I like your approach over adding the class, as this doesn't require me to change my markup. Thanks again for the help
  • Paolo Bergantino
    Paolo Bergantino almost 15 years
    @Scott: I would imagine that's the behavior desired. If you have several ULs you would want to put the border on each last child. Thanks for the note, though.
  • JoshBerke
    JoshBerke over 11 years
    last-child didn't work on IE7....don't recall why I had a div in the li...been to long