Coderama
Coderama

Reputation: 11352

Applying last-child to element not working

Given I have the following tags:

<div id="div-one">
    <div class="div-two">some </div>
    <input type="hidden" value=""/>
    <div class="div-two">some </div>
    <input type="hidden" value=""/>
    <div class="div-two">some </div>
    <input type="hidden" value=""/>
</div>

When I try to apply a style to the last "div-two" element using this css syntax:

#div-one div.div-two:last-child  { border-bottom:solid 1px #999; }

It doesn't work unless I remove the hidden fields. Any suggestions as to why?

Upvotes: 12

Views: 17520

Answers (2)

Useless Code
Useless Code

Reputation: 12402

If you can't use last-of-type like @BoltClock suggested you could just add a second class to the last .div-two in the group.

http://jsfiddle.net/watss/

<div class="div-two last">some </div>

and

#div-one > .div-two.last { border-bottom:1px solid; background:yellow; }

or better yet

#div-one > .last { border-bottom:1px solid; background:yellow; }

Upvotes: 2

BoltClock
BoltClock

Reputation: 723638

Your selector doesn't work for your current markup because the last child is an input, not a div.div-two.

Is div#div-one only going to contain those two kinds of elements? If so, you can use :last-of-type instead, which picks the last div (though regardless of its class):

#div-one div:last-of-type { border-bottom:solid 1px #999; }

However if your inner div elements have other classes besides .div-two, it will be pretty difficult to choose the last .div-two element. Your given code makes it easy because div and input are distinct element types and only the .div-two class is present.

Upvotes: 19

Related Questions