Question

I have this HTML --

<ul class="parent">
<li>
    <div class="child-1 x">
        <div class="child-2 x">test</div>
    </div>
</li>
<li>
    <div class="child-1 x">
        <div class="child-2 x">test</div>
    </div>
</li>
<li>
    <div class="child-1 x">
        <div class="child-2 x">test</div>
    </div>
</li>
</ul>

And this CSS --

.x{
    border:1px solid black;
    padding: 10px;
}
.child-1:last-child{
    border-color:red;
}

http://jsfiddle.net/BDj2h/1/

Im trying to apply red border only to the last child-1 div. But its not happening. CSS last-child pseudo class checks whether its the last element inside its immediate parent, not in the whole DOM(which was my wrong understanding).

Any idea how to do this with css only?

Was it helpful?

Solution

li:last-child .child-1

Would have the same effect.

JSFiddle

OTHER TIPS

:last-child1 pseudo won't respect the last declared class, it just tracks the last instance of the element in the parent/child relation.

1 Same as :nth-last-child(1). The :last-child pseudo-class represents an element that is the last child of some other element.

So for example, if you've something like

Writing something like

div.wrap div.blow:last-child {
   /* .blow doesn't make any sense there, CSS will look up 
       for last div element nested inside .wrap */
}

In this case, you can try using

.parent li:last-child div[class^="child-1"] {
    border-color:red;
}

Or simply

.parent li:last-child div.child-1.x {
   border-color:red;
}

Demo


Note: last-child is somewhat loose pseudo, as it will simply ignore the element if it's not the last child of the parent element, so here, last-of-type comes in to action where it selects last type of an element regardless of it's DOM level.

ul li:last-child > div.child-1 {
    border-color:red;
}

Example: http://jsfiddle.net/BDj2h/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top