how to select the last div that has class 'visible' in a container using CSS selector?

Hi guys, i want to select the last div has class visible using css selector. Is this possible? Here is my example:
<div class="container">
<div class="visible">Item 1</div>
<div class="visible">Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</div>
// => Item 2
<div class="container">
<div class="visible">Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</div>
// => Item 1
<div class="container">
<div class="visible">Item 1</div>
<div class="visible">Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</div>
// => Item 2
<div class="container">
<div class="visible">Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</div>
// => Item 1
8 Replies
empty
emptyOP2w ago
It not work
No description
Mannix
Mannix2w ago
.container > :nth-last-child(-n + 1 of .visible){
color:red;
}
.container > :nth-last-child(-n + 1 of .visible){
color:red;
}
empty
emptyOP2w ago
It works but I dont really understand the selector. As I understand it will go through bottom to the top of the container and of keyword means the child has class .visible right?
Mannix
Mannix2w ago
Honestly no idea i just used https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child and did trial and error to get expected result. I'm really bad with the nth selector but somehow managed to make it work 😛
MDN Web Docs
:nth-last-child() - CSS: Cascading Style Sheets | MDN
The :nth-last-child() CSS pseudo-class matches elements based on their position among a group of siblings, counting from the end.
Mannix
Mannix2w ago
thanks to Kevin's latest video i found simpler solution
.container > :nth-last-child(1 of .visible){
color:red;
}
.container > :nth-last-child(1 of .visible){
color:red;
}
basically this goes from the bottom and selects only first item that it finds with the class visible
Chris Bolson
Chris Bolson2w ago
So changing that "1" to a "2" would select the penultimate element with the class .visible, interesting! I need to explore the "of" syntax more 🤔
.container > :nth-last-child(2 of .visible){
color:red;
}
.container > :nth-last-child(2 of .visible){
color:red;
}
LachsDuJour
LachsDuJour2w ago
Be careful: only 93.23% of browsers support this. Dont use it on "big" pages
Want results from more Discord servers?
Add your server