DEV Community

Cover image for CSS nth-child trick: get the first/last half of elements
Rae Liu
Rae Liu

Posted on • Edited on

7 5

CSS nth-child trick: get the first/last half of elements

nth-child is a common way to style a specific element. For example 2n+1 is for all odd elements, and 2n is for all even ones.

But how to choose the first/last half of elements without any JavaScript? One of my projects had this wired situation, and I prefer to not use any JavaScript codes.

Negative child range and nth-last-child

:nth-child(n+2) means all elements without the first one.
:nth-child(-n+2) means all elements without the last and the second ones.
nth-last-child(n+2) will select elements from the second last one to the first one.
nth-last-child(-n+2) will select elements from the second last one to the last one.
Alt Text

Last half of elements

According the example image, let's assume there are 4 elements -

half or more elements



:nth-child(n+2):nth-last-child(-n+2)

Enter fullscreen mode Exit fullscreen mode




half or less elements




nth-child(n+3):nth-last-child(-n+2)

Enter fullscreen mode Exit fullscreen mode




last half or more elements, top to 12




first-child:last-child,
nth-child(n+2):nth-last-child(-n+2),
nth-child(n+3):nth-last-child(-n+3),
nth-child(n+4):nth-last-child(-n+4),
nth-child(n+5):nth-last-child(-n+5),
nth-child(n+6):nth-last-child(-n+6)

Enter fullscreen mode Exit fullscreen mode




Converts it to SCSS

What if there are 100 elements? You have to write 50 lines in CSS...
But we can make a @mixin, then add a max number.



@mixin last-half-of-nth($maxNumber){
&:first-child:last-child{
color: white;
background: darkblue;
}
@for $n from 2 through $maxNumber{
&:nth-child(n+#{$n}):nth-last-child(-n+#{$n}){
color: white;
background: darkblue;
}
}
}

Enter fullscreen mode Exit fullscreen mode




last half or more, top to 100




@include last-half-of-nth(50);

Enter fullscreen mode Exit fullscreen mode




Limitation

You have to know the max number of the elements, otherwise it won't work. But this trick is still good for pure CSS without any JavaScript codes.

Preferences

https://stackoverflow.com/questions/15466898/selecting-half-the-elements-with-nth-child

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay