Skip to main content
CSS Tip

Select the first & last element with a class

Do you want to select the first and last element with a specific class? It's possible and you can do it using 2 different methods!

/* First element with class "cat" */
.cat:not(.cat ~ *) {}
/* OR */
:nth-child(1 of .cat) {}


/* Last element with class "bird" */
.bird:not(:has(~ .bird)) {}
/* OR */
:nth-last-child(1 of .bird) {}

See the Pen Untitled by Temani Afif (@t_afif) on CodePen.