The issue lies within this CSS and HTML. Here is a link to jsFiddle with the sample code.
HTML
<ul>
<li class"complete">1</li>
<li class"complete">2</li>
<li>3</li>
<li>4</li>
</ul>
CSS
li.complete:last-child {
background-color:yellow;
}
li.complete:last-of-type {
background-color:yellow;
}
Shouldn't either of these lines of CSS target the last li element with the "complete" class?
This query in jQuery doesn't target it either:
$("li.complete:last-child");
But this one does:
$("li.complete").last();
li {_x000D_
background-color: green;_x000D_
}_x000D_
li.complete:first-child {_x000D_
background-color: white;_x000D_
}_x000D_
li.complete:first-of-type {_x000D_
background-color: red;_x000D_
}_x000D_
li.complete:last-of-type {_x000D_
background-color: blue;_x000D_
}_x000D_
li.complete:last-child {_x000D_
background-color: yellow;_x000D_
}
_x000D_
<ul>_x000D_
<li class="complete">1</li>_x000D_
<li class="complete">2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
</ul>
_x000D_
This question is related to
html
css
css-selectors
In addition to Harry's answer, 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. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."
Suppose this is my selector: a:last-child {}
This works:
<div>
<a></a>
<a>This will be selected</a>
</div>
This doesn't:
<div>
<a></a>
<a>This will no longer be selected</a>
<div>This is now the last child :'( </div>
</div>
It doesn't because the a
element is not the last element inside its parent.
It may be obvious, but it was not for me...
I encounter similar situation. I would like to have background of the last .item
to be yellow in the elements that look like...
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
...
<div class="item">item x</div>
<div class="other">I'm here for some reasons</div>
</div>
I use nth-last-child(2)
to achieve it.
.item:nth-last-child(2) {
background-color: yellow;
}
It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick
Source: Stackoverflow.com