Daniel Williams Daniel Williams - 5 months ago 11
CSS Question

Select last child except if it is also first child

I have set up a rule for the last LI tag of my UL:

.className li:last-child {
stuff: here;
}


Am I able to set a rule in the CSS that says "apply this style to the last LI tag EXCEPT if the
last-child
is also the
first-child
", i.e. there is only one LI tag in the OL.

Answer

You can use it together with :not() selector:

li:last-child:not(:first-child) {
  color: red;
}
<ul>
  <li>item a</li>
  <li>item b</li>
  <li>item c</li>
</ul>

<ul>
  <li>only item</li>
</ul>

Either of these selectors will also work in the case:

li:last-of-type:not(:first-of-type) {
  color: red;
}

li:last-of-type:not(:only-of-type) {
  color: red;
}