'How to apply CSS to nth nested element? [duplicate]

I've got this structure in my HTML and I'm trying to apply some css to the last element of class target but I can't figure out how to do it or if it is possible. It seems like when I try things like :last-child or :last-of-type it just applies the css to all of the target elements since it considers them to be the only element.

<div className="parent"> 
  <div>
    <div className="target"></div>
  </div>
  <div>
    <div className="target"></div>
  </div> 
  <div>
    <div className="target"></div>
  </div>
</div>


Solution 1:[1]

If you want to apply the CSS last-child then you can try this code: You can add the class for every div

.parent div:nth-last-child(1) .target{
background: #000000;
color: #fff;
}

Solution 2:[2]

Try something like that

.parent > div {
    width: 50px;
    height: 50px;

    border: solid 2px black;

    background-color: red
}
.parent div:last-child {
    background-color: blue
}

Solution 3:[3]

Maybe I figured out what’s happened with your code. Writing .target:last-child you select any div element with .target class that is the last child of another element. Your CSS code is applied to every .target element because each of them are nested in a separated div, so every .target div is the last (and unique) child of each div within is nested. So To do what you want, try this HTML:

<div class="parent">
        <div class="target"></div>
        <div class="target"></div>
        <div class="target"></div>

and this CSS:

.target {
    width: 100px;
    height: 100px;
    background-color: red;
    margin-top: 50px;
}

.target:last-child {
    background-color: blue;
}

Be aware that if you will have another div with .parent class which contains element with .target class in your project, this CSS will be apllied also to these others code. If you try to copy and past your HTML more times you'll be able to see what I'm talking about. I hope I have been helpful!

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 Sahil Palad
Solution 2 bubi
Solution 3 Andrea