{"id":342736,"date":"2021-06-29T07:37:21","date_gmt":"2021-06-29T14:37:21","guid":{"rendered":"https:\/\/css-tricks.com\/?p=342736"},"modified":"2021-06-29T13:22:12","modified_gmt":"2021-06-29T20:22:12","slug":"nth-child-between-two-fixed-indexes","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/nth-child-between-two-fixed-indexes\/","title":{"rendered":":nth-child Between Two Fixed Indexes"},"content":{"rendered":"\n

I needed to select some elements between two fixed indexes the other day\u2009\u2014\u2009like literally the second through fifth elements. Ironically, I have a whole post on “Useful :nth-child Recipes”<\/a> but this wasn’t one of them. <\/p>\n\n\n\n

The answer, it turns out, isn’t that<\/em> complicated. But it did twist my brain a little bit. <\/p>\n\n\n\n\n\n\n\n

Say you want to select all divs from the second one and beyond:<\/p>\n\n\n\n

div:nth-child(n + 2) {\n\n}\n\/* [ ]  [x]  [x]  [x]  [x]  [x]  [x]  [x], etc. *\/<\/code><\/pre>\n\n\n\n

That makes logical sense to me. If n<\/code> is 0<\/code>, the expression is 2<\/code>, and n<\/code> increments upwards from there and selects everything beyond it.<\/p>\n\n\n\n

But then how do you “stop” the selecting at a specific index? Like… <\/p>\n\n\n\n

\/* Not real *\/\ndiv:nth-child(minmax(2, 5)) {\n\n}\n\/* [ ]  [x]  [x]  [x]  [x]  [x]  [ ]  [ ], etc. *\/<\/code><\/pre>\n\n\n\n

Well, we can do the opposite thing, selecting only the first set of elements then stopping (constraining in the other direction) by reversing the value of n<\/code>. <\/p>\n\n\n\n

div:nth-child(-n + 6) {\n\n}\n\/* [x]  [x]  [x]  [x]  [x]  [ ]  [ ]  [ ], etc. *\/<\/code><\/pre>\n\n\n\n

That will select the the first five elements and then stop because, as n<\/code> gets bigger, the expression value goes to 0<\/code> and into negative numbers. <\/p>\n\n\n\n

So, the CSS trick here is to combine both of those :nth-child<\/code> expressions. <\/p>\n\n\n\n

We know that CSS pseudo-selectors are additive in the sense that they must both<\/em> be true in order to select them.<\/p>\n\n\n\n

a:first-child:hover {\n  \/* selects the <a> if it is BOTH the first child and in a hover state *\/\n}<\/code><\/pre>\n\n\n\n

To accomplish the idea of “2 and over” and “5 and under” we chain the pseudo-selectors:<\/p>\n\n\n\n

div:nth-child(n + 2):nth-child(-n + 6) {\n  background: green;\n}<\/code><\/pre>\n\n\n\n

That’ll do:<\/p>\n\n\n\n