Automate :nth-child Selectors with Family.scss Mixins

Sass is the best way to manage modern CSS and mixin libraries can save even more time during the development cycle.

These mixins work like automated codes or functions that you call in your main Sass files. Some mixins are more general while others are very specific such as the Family.scss library.

This free library offers 26 mixins for running complex :nth-child selectors without memorizing all that code.

Most developers know about the :nth-child selector and by default, it’s certainly not complicated. You simply pass a numeric selector, for example :nth-child(2) where the belonging style rules apply to every second child of the parent element.

However, this can get far more complex when you want to select dynamic elements (such as first & last) or when you want to select a small handful of elements (such as the first three children).

This is where Family.scss can help. It’s a very small library and it contains 26 solutions for child selectors ranging from basic to super complex. Each mixin has a demo on the homepage, which you can browse and filter as needed.

Here are some interesting examples to show off what this library can do:

  • after-first(5) – select all elements after the first 5 children
  • from-end(3) – select the 3rd to last child element
  • all-but(3) – select all children except the 3rd
  • even-between(3, 12) – select all even children between the 3rd & 12th elements

There are dozens more you can browse through and they each have demos to help you visualize how they work.

A few advanced mixins rely on quantity queries that pick elements which are “at least” or “at most” fixed to a certain range. For example, you can select all children for parent elements that have at least 5 children (or more).

These ideas can be confusing when reading about them but the live demos really make it all crystal clear.

Family.scss mixins

To dig in, you can download a copy of this mixin library from the GitHub repo, along with all of these demos. And, you can share your thoughts or questions with the project’s creator on Twitter @LukyVJ.