1

I am trying to find last-child on the basic of class and wants to apply some styling but using :last-child selector its not as per expectation. I have a limitation I don't want to use java script and due the elements length is not fixed I can not use nth selector.

Used HTML Markup

<ul>
    <li class="a">First</li>
    <li class="a">Second</li>
    <li class="a">Third</li>    
    <li class="b">First</li>
    <li class="b">Second</li>
    <li class="b">Third</li>    
    <li class="c">First</li>
    <li class="c">Second</li>
    <li class="c">Third</li>        
</ul>    

Used Css

.a{
    color:red;
}
.b{
    color:blue;
}
.c{
    color:green;
}

.a:last-child{
    color:green;
}
.b:last-child{
    color:red;
}
.c:last-child{
    color:blue;
}

Any help to how to approach this problem.

Soarabh
  • 2,910
  • 9
  • 39
  • 57

4 Answers4

3

If you are trying to target last-child of ul element, than this is enough

ul li:last-child {

}

Demo

Or if you want to style last child of each unique class than you need than last-child won't work here, you need to use nth-of-type instead or a formula like

Demo

ul li:nth-child(3n+3) { /* This way you don't have to use classes too */
    color: red;
}

Note: If you are generating elements dynamically than as of now there's no way to select last-child of element with a unique class. SO you have to use nth-child, nth-of-type or a formula like I mentioned


Other way you can do this is, programatically create an ul element after n iteration and in your loop and use this selector

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
1

First of all you're missing the point in front of your classnames, but anyway this wouldn't solve your problem. As you seem to generate your list programmatically , I would suggest adding a class to each last item with a certain class. Or alternatively use Javascript, which you don't want to...

Laurent S.
  • 6,816
  • 2
  • 28
  • 40
1

Suppose it will be easier to add some additional class to specify the last element or by using JS.

For instance, you may do something like this:

<ul>
    <li class="a ">First</li>
    <li class="a ">Second</li>
    <li class="a last">Third</li>    
    <li class="b">First</li>
    <li class="b">Second</li>
    <li class="b last">Third</li>    
    <li class="c">First</li>
    <li class="c">Second</li>
    <li class="c last">Third</li>        
</ul>    

And css:

.a{
    color:red;
}
.b{
    color:blue;
}
.c{
    color:green;
}

.a.last{
    color:green;
}

.b.last{
    color:red;
}

.c.last{
    color:blue;
}

http://jsfiddle.net/ud8KZ/1/

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
0

you are not using dot in last three css class

.a:last-child{
    color:green;
}
.b:last-child{
    color:red;
}
.c:last-child{
    color:blue;
}

I think that's why you are not getting output

Ravi Pal
  • 395
  • 1
  • 7
  • 22