Eva
Eva

Reputation: 5077

why is last-child not working in this example?

In this example, the li:last-child definition comes after the nth-of-type definition, but for some reason the element is styled with the definition that appears first instead of the one that appears last. What's the reason for this? (the last child should be showing up as blue)

HTML:

<ul></ul>

Javascript:

$(function(){
   var $ul = $('ul');
   var $console = $('div.console'); 

    for( var i = 0; i < 15; i++ ){
      $ul.append('<li>'
        + 'Latest Download ' + (i + 1)
        + '</li>'
     )

     if( ! ((i + 1) % 5) ){
       $ul.append('<div>clear div</div>');   
     }



    }
});

CSS:

ul {
    list-style: none;
}

ul > li {
    display: inline-block;
    padding: 5px;
    background-color: lightblue;

    border: 1px solid blue;

    color: green;
    font-family; Arial,Helvetica;
}

ul > li:nth-of-type(5n) {
    color: yellow;
}

ul > li:first-child {
    color: red;
}

ul > li:last-child {
    color: blue;
}

JS Fiddle: http://jsfiddle.net/eQRgw/1/

Upvotes: 0

Views: 81

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The problem is li element is not the last child, the div is the last child of the ul element so :last-child will match only the last div element

use last-of-type

ul > li:last-of-type {
    color: blue;
}

Demo: Fiddle

Note: ul should not have div as a child

Upvotes: 2

Related Questions