I have the following HTML structure:
<ol>
<li><a id="a" href="#">Not this</a></li>
<li><a id="b" href="#">Not this</a></li>
<li><a id="c" href="#">This one</a></li>
<li class="active"><span>Not this</span></li>
</ol>
I want to select #c via CSS. I have tried:
ol > li:not(.active):last-child > a {
border: 1px solid green;
}
As I understand it li:not(.active) selects all the li elements but the one with class .active.
On this selection I use :last-child to get the last of these li elements. But this wont work. What's wrong? Is it possible what I'm trying to achieve?
Thank you very much :)
PS: The list length is dynamic and the elements does not have any id that could be used for CSS selection (I just used some in the example to clarify which element I want to select) ;)
The pseudo code that you wrote works! There's no last-child
of <li>
with no active
class. So your code fails any time! Check with another one in which, the last <li>
doesn't have an active
.
Or you need to use last-of-type
. Check the fiddle:
ol > li:not(.active):last-child > a {
border: 1px solid green;
}
ol > li:not(.active):last-of-type > a {
border: 1px solid green;
}
<ol>
<li><a id="a" href="#">Not this</a></li>
<li><a id="b" href="#">Not this</a></li>
<li><a id="c" href="#">This one</a></li>
<li class="active"><span>Not this</span></li>
</ol>
<ol>
<li><a id="a" href="#">Not this</a></li>
<li><a id="b" href="#">Not this</a></li>
<li class="active"><span>Not this</span></li>
<li><a id="c" href="#">This one</a></li>
</ol>
One thing to note is, last-of-type
doesn't consider :not()
. Check CSS: How to say .class:last-of-type [classes, not elements!]! You might need to use JavaScript or jQuery for this.
Partial Solution
If you know that the Not this
always occurs in the last, you can use nth-last-child(2)
:
ol > li:not(.active):nth-last-child(2) > a {
border: 1px solid green;
}
<ol>
<li><a id="a" href="#">Not this</a></li>
<li><a id="b" href="#">Not this</a></li>
<li><a id="c" href="#">This one</a></li>
<li class="active"><span>Not this</span></li>
</ol>