':not(:last-of-type) not working for class

Why doesn't :not(:last-of-type) work in the following situation? How can I fix it?

JSFiddle: http://jsfiddle.net/C23g6/589/

HTML:

<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">Shouldn't be Red</div>
<div class="hello">------------------</div>

CSS:

.comment:not(:last-of-type) {
    color: red;
}


Solution 1:[1]

As mentioned, the reason is because :last-of-type matches an element that is the last sibling of its element type, in this case div. Since the last div isn't the last .comment, it doesn't match.

Unlike for the first element of a class, there is no way to use pure CSS to match the last element of a class, not even with an override. You should either use information about the existing structure to create a selector that will match the element you're looking for, such as:

.comment:not(:nth-last-child(2))

Or failing that, add an extra class name to the last .comment and exclude that, or otherwise alter the structure itself to accommodate your needs.

Solution 2:[2]

if your structure never change , then :

div {
    color:red;
}
:nth-last-of-type(2) {
    color: black;
}

Would be the simple way to do : DEMO , demo 2

:not() has still limitation.

Solution 3:[3]

If your html structure doesn't change, you can use it as the .comment div is always followed by the .hello div.

.comment:nth-last-of-type(n+4) {
    color: red;
}
<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">This is Red</div>
<div class="hello">------------------</div>
<div class="comment">Shouldn't be Red</div>
<div class="hello">------------------</div>

"The :nth-last-of-type() CSS pseudo-class matches elements based on their position among siblings of the same type (tag name), counting from the end."

In: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 G-Cyrillus
Solution 3