1

So I tried googling this but find it quite difficult to get the right search terms in.

I'm trying to namespace a pseudo-selector on only a certain class

In this example, without the class the last Hi should be blue. I would expect this code to turn the second span blue, which is not the case. Am I doing something wrong or do I have an unreasonable expectation of what CSS should be doing?

span.dinosaur:last-child {
  color: blue;
}
<body>
  <span class='dinosaur'>Hi</span>
  <span class='dinosaur'>Hi</span>
  <span>Hi</span>
  <span>Hi</span>
</body>
Stefan Dorunga
  • 679
  • 6
  • 18
  • Possible duplicate of http://stackoverflow.com/questions/6401268/how-do-i-select-the-last-child-with-a-specific-class-name-in-css or http://stackoverflow.com/questions/7298057/css-last-child-selector-select-last-element-of-specific-class-not-last-child-i – Hashem Qolami Oct 22 '14 at 20:12

1 Answers1

4

I would expect this code to turn the second span blue, which is not the case.

You have a fundamental misunderstanding of the :last-child pseudo-class; it matches only if the element to which the pseudo-class is applied, only if that element is the last-child of its parent. It is not equivalent to :last-of-type() selector (and even that pseudo-class disregards class-names and id, and selects an element based on its element-type (<div>, <p> etc).

In future, :nth-match() might serve your purpose, but that's yet to be implemented (so far as I'm aware) in any browser, and is part of the Selectors Level 4 module.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Ok, that seems reasonable enough, and kind of the answer I expected. So if I wanted to do what I'm trying to do, what would the best way to approach it be? – Stefan Dorunga Oct 20 '14 at 16:47
  • 1
    @StefanDorunga To expand on what David said, think of `span.dinosaur:last-child` as first selecting the last child span, and then only matching if that span has the dinosaur class. It won't do what I think you're thinking it will do, and select the last child span that has the dinosaur class. It's a common misconception. – j08691 Oct 20 '14 at 16:47
  • So for now, without javascript I have no solution? – Stefan Dorunga Oct 20 '14 at 17:08
  • I'm afraid not; unfortunately. – David Thomas Oct 20 '14 at 17:09