-2

Im trying to select the last two div's with class row in my container div

I have tried this code

.child1 {
  padding: 5px;
  background-color: red;
  margin: 5px;
  width: 30%;
}

.parent .child :nth-last-child(-n+2) {
  background-color: green;
}
<div class="parent">
  <div class="child">
    <div class="child1">test1</div>
    <div class="child1">test2</div>
    <div class="child1">test3</div>
    <div class="child1">
      test4
      <div class="child2">test42</div>
    </div>
    <div class="child1">test5</div>
    <div class="child1">test6</div>
  </div>
</div>

Im expecting that the backgrounds of test5 and test6 is going to be green. The problem is the background of test42 is also comming green.

connexo
  • 53,704
  • 14
  • 91
  • 128

1 Answers1

3

Use the child combinator > to only target direct children:

.child1 {
  padding: 5px;
  background-color: red;
  margin: 5px;
  width: 30%;
}

.parent .child>:nth-last-child(-n+2) {
  background-color: green;
}
<div class="parent">
  <div class="child">
    <div class="child1">test1</div>
    <div class="child1">test2</div>
    <div class="child1">test3</div>
    <div class="child1">
      test4
      <div class="child2">test42</div>
    </div>
    <div class="child1">test5</div>
    <div class="child1">test6</div>
  </div>
</div>
connexo
  • 53,704
  • 14
  • 91
  • 128