Explain Codes LogoExplain Codes Logo

Why does .class:last-of-type not work as I expect?

html
css-selectors
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 14, 2025
TLDR

Here's the TL;DR for the folks in a hurry: :last-of-type tumble-dries with types of elements, not classes. It targets the last sibling of a type, not the last of .class stars on your webpage. Try this instead:

.class:not(.class ~ .class) { /* styles */ }

This piece of magic targets .class elements that do not have any co-star siblings with the same class, effectively placing the spotlight on the last-of-its-kind.

The sibling selector sideshow

Siblings in CSS? Yes, they're a thing. Understanding sibling combinators and pseudo-class selectors is like decoding the Da Vinci Code of CSS. When you need to style the last among similar elements, shepherding them all under .class:last-child might lead a few black sheep into your fold. Better to emphasize performance by enlisting class selectors, which browsers can run like Usain Bolt compared to the tortoise-paced pseudo-selectors.

Better performance and future wearable

Let's decorate our markup like we're prepping for a carnival — with classes and IDs galore. This enhances styling speed and gives a performance boost like a CSS energy drink. In our quest for CSS enlightenment, glancing at the fortunes contained in future CSS standards like CSS 4 selectors will put us in pole position to harness them upon arrival.

Last-of-type carried away by classes? Revolve towards the :not() and :last-child selectors. The :not() pseudo-class is like the Swiss army knife of selectors, providing a deeper level of control over the affected elements. If your target last element is also the last kid in line, :last-child is your best friend.

p.visible:last-child { /* Makes the last visible paragraph stand out. Zero stealth mode! */ display: block; }

Warm coffee with browser compatibility

With an array of browser compatibility, deciding the best CSS selector can feel like choosing your coffee order. CSS3 selectors have universal express delivery, while CSS4 offers tantalizing brews in the pipeline. Sites like dabblet.com give you a taste test of these varying flavors.

The ‘display’ toggle game

Finally, remember the CSS display property is vital for hide 'n' seek with your elements. Making the display property your tag partner, you'll turn visibility on and off more efficiently than swapping Halloween costumes.