Alex McCabe Alex McCabe - 1 month ago 5
CSS Question

CSS Get last-child that doesn't have a class

Here is a tricky challenge for you guys, CSS selector to get the

:last-child
that doesn't have a class.

What I have tried so far:

.nav-item:not(.nav-item--mobile):last-child {...}
.nav-item:last-child:not(.nav-item--mobile) {...}


I have similar query selectors that do some fun stuff, so I'd rather try and do this via CSS. The mobile items can be variable in quantity.

// Get the first child in the list when there are n or more, and
// they are not mobile. Yes, this actually works.
.nav-item:first-child:nth-last-child(n+7):not(.nav-item--mobile)


The following will give me the last child in all cases, but I want the last child that isn't a mobile only child.

.navigation-item--top:last-child


Target



generic generic generic generic generic mobile mobile
^
target this one


HTML



<ul class="nav-items-list">
<li class="nav-item"></li>
<li class="nav-item"></li>
<li class="nav-item"></li>
<li class="nav-item"></li>
<li class="nav-item nav-item--mobile"></li>
<li class="nav-item nav-item--mobile"></li>
</ul>


Yes I could figure out which is the correct one in the generated navigation, or I could find it with JS.

Answer

Unfortunately what you want cannot be achieved using CSS only.

:last-child asks only one question, no matter what else you specify: Am I the last child of my parent element?

Sadly, there is no :last-of-class, only :last-of-type, but this cares only about element type.

It is not even planned for selectors level 4 that you can specifiy a class or other limiting property. See

https://www.w3.org/TR/selectors4/#the-last-child-pseudo

Comments