Explain Codes LogoExplain Codes Logo

Css selector for other than the first child and last child

html
css
selectors
performance
Anton ShumikhinbyAnton Shumikhin·Aug 10, 2024
⚡TLDR

To exclude the first and last children in CSS selections, use the :not() pseudo-class with :first-child and :last-child:

#navigation ul li:not(:first-child):not(:last-child) { /* Styles for intermediate children, aka the middle child syndrome */ }

This targets intermediate children across all elements, applying styles only to the non-terminal children.

An overview of :not()

Efficiency of selectors

To keep your CSS tidy, use :not() for excluding specific elements without the convoluted logic sometimes required by other selectors. The :not() pseudo-class cannot include multiple conditions inside its parentheses, so li:not(:first-child, :last-child) is a no-go.

Playing the specificity game

The introduction of :not() increases the specificity of your selectors, so beware. Adding multiple :not() selectors further ups the ante, just keep in mind they are still less specific than a class or ID selector.

In case of unusual HTML or browsers

In instances where :first-child and :last-child won't play nice (looking at you, Internet Explorer), the :nth-child() selector might be your knight in shining armor.

Beyond bare selectors

Exploiting :nth-child() and :nth-last-child()

When :first-child and :last-child are too vanilla for your project, step up your game with the :nth-child(n) and :nth-last-child(n) selectors. Unleash their power to skip or select children based on mathematical patterns or specific counts.

CSS with caution

Don't go overboard with :not() - while it can be a power tool, it can also bog down browser performance if overused. Use it as the special sauce, not the main course.

Embracing classes

Styling a specific class but need to exclude a few black sheep? No worries, :not() has your back:

.special:not(:first-child):not(:last-child) { /* Beware Sith lords! Styles for non-terminal .special class members */ }