Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  • Here's a link to the jsfiddle: http://jsfiddle.net/67qYJ/1/
  • Using Google Chrome v12.0.742.100
  • It is NOT an option to place the hidden tags elsewhere
like image 791
Coderama Avatar asked Jun 23 '11 23:06

Coderama


People also ask

Why is my last child not working?

:last-child will not work if the element is not the VERY LAST element. I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container.

How do I choose my last nth child?

The nth-last-child pseudo-class is specified with a single argument, which represents the pattern for matching elements, counting from the end. :nth-last-child( <nth> [ of <complex-selector-list> ]? )

How do you target the last two child in CSS?

The examples of an+b are as follows: :nth-last-child(odd) /* represents all odd foo elements in their parent element, counting from the last one */ :nth-last-child(-n+2) /* represents the two last elements */


2 Answers

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.

like image 94
BoltClock Avatar answered Oct 22 '22 00:10

BoltClock


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; }
like image 42
Useless Code Avatar answered Oct 21 '22 23:10

Useless Code