3

EDIT:The problem is i am using react so i cannot wrap these elements using another div because they have many parents. Is there any way to look every div in the page which have class .my-class and show last instance of it.

I want to change the background color of the last div instance. In code div which contains 'third'.

https://jsfiddle.net/a694du2h/

But the first div becomes red too. I know it is because they do not have the same parent. Is there any way to do what I want?

<html>

<head>
  <style>
    .my-class:last-of-type {
      background: #ff0000;
    }
  </style>
</head>

<body>
  <div>
    <div class='my-class'>first</div>
  </div>
  <div class='my-class'>second</div>
  <div class='my-class'>third</div>
</body>

</html>
Ali Korkmaz
  • 105
  • 6
  • Will your first/second/third items always have the same structure, or can each of them be inside wrapping `div`s? – DBS Aug 14 '19 at 15:45
  • @Paulie_D I don't think this is a duplicate of the question you've linked. – Itay Aug 14 '19 at 15:49
  • It is. The question is based on a misunderstanding of the "power" of `nth`. The OP wants `last-of-class` and there is **no such selector**. – Paulie_D Aug 14 '19 at 15:56

1 Answers1

0

Bind your rule to those classes that are immediately below the body parent.

body > .my-class:last-of-type {
  background: #ff0000;
}

https://jsfiddle.net/760Ljbca/

PaulProgrammer
  • 16,175
  • 4
  • 39
  • 56
  • 1
    I cannot wrap these elements using another div because they have many parents. Is there any way to look every div in the page which have class .my-class and show last instance of it. – Ali Korkmaz Aug 14 '19 at 15:58
  • This isn't wrapping in a div, it's using the natural parent in your example. There is no other way to select the "last" of a class (see comment on question from @paulie_d). You could use javascript to dynamically evaluate the DOM for the last class, or emit a "special" class in react. – PaulProgrammer Aug 14 '19 at 16:01