DEV Community 👩‍💻👨‍💻

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

Posted on • Updated on

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

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.