JSFiddle - React, Tailwind, and code Playground
https://stackoverflow.com/questions/77479663/css-how-to-conditionally-select-the-last-x-nth-last-of-type-only-when-any-of-th
by moob
HTML
<div class="container">
<div id="d0" class="normal selected">0</div>
<div id="d1" class="normal">1</div>
<div id="d2" class="normal">2</div>
<div id="d3" class="normal">3</div>
<div id="d4" class="normal">4</div>
<div id="d5" class="normal">5</div>
</div>
CSS
.selected {
outline:2px dotted;
}
/*
if the last nth is selected,
or HAS an adjacent sibling which is selected
then highlight it and the siblings:
.container div:nth-last-of-type(3):is(.selected),
.container div:nth-last-of-type(3):has(~.selected),
.container div:nth-last-of-type(3):is(.selected) ~ div,
.container div:nth-last-of-type(3):has(~.selected) ~ div {
background: green;
}*/
.container:has(.selected:nth-last-of-type(-n + 3)) > :nth-last-of-type(-n + 3) {
background-color: #A00;
}
JavaScript
/* For demo. Set .selected on click */
const items = document.querySelectorAll(".container > div");
items.forEach(item => {
item.addEventListener('click', onclick);
});
function onclick(){
document.querySelector(".selected").classList.remove("selected")
this.classList.add("selected");
}