How to Select the Last Element With a Specific Class, Not Last Child Inside of Parent

How can I select the last element with a specific class, not last child inside of parent?

:last-child only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type

As per @BoltClock's comment, this is only checking for the last article element, not the last element with the class of .comment.

body {
background: black;

.comment {
width: 470px;
border-bottom: 1px dotted #f0f0f0;
margin-bottom: 10px;

.comment:last-of-type {
border-bottom: none;
margin-bottom: 0;
<div class="commentList">
<article class="comment " id="com21"></article>

<article class="comment " id="com20"></article>

<article class="comment " id="com19"></article>

<div class="something"> hello </div>

Apply CSS to last element of specific class

Last element using .class is not possible. In your case you can use nth-last-child property.

 .blog-posts div:nth-last-child(2) {
background: #ff0000;


How can I select all children of an element except the last child?

You can use the negation pseudo-class :not() against the :last-child pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:

:not(:last-child) { /* styles */ }

I need to select (not last child) only if it has a specific class

Instead of applying padding-right to everything except the last one, you can apply padding-left to everything except the first one. This will make your code much more intuitive and simple to read.

Check this out:

 a[class^=action--] + a {
padding-left: 5px;

 a[class^=action--] + a {     padding-left: 5px; }
<table>    <tr>        <td><img src="" height="40" width="40" /></td>        <td>Triple monochromator for Raman</td>        <td>            <a href="i"><img src=""/></a>        </td>        <td>            <a class="action--edit"><i class="icon-building"><img src=""/></i></a>            <a class="action--delete"><i class="icon-building"><img src=""/></i></a>            <a class="action--view"><i class="icon-building"><img src=""/></i></a>        </td>    </tr></table>

How can I get the last matched element with a CSS selector that has different parents?

This is not a great solution but it does what you want in this specific example

*:last-of-type > .something:last-of-type {
background-color: black;
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>

CSS selector for other than the first child and last child


#navigation ul li:not(:first-child):not(:last-child) {

CSS selector with nth-child works but not last-child

use .child-div:nth-last-child(1) { }

The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child.

Related Topics

Leave a reply