How to select a range of elements in a repeating pattern

Let's say that in 4 lines there are 12 elements.

| 1 || 2 || 3 | | 4 || 5 || 6 | | 7 || 8 || 9 | | 10 || 11 || 12 | 

I want to choose both the style of the 2nd row and 4th row, How to do this?

Note that the strings are not in different HTML elements, in fact this is all the ul li element.

Desired Result:

  | 1 || 2 || 3 | |--4---||--5---||--6---| | 7 || 8 || 9 | |--10--||--11--||--12--| 

I tried to play with this:

 li:nth-child(n+4) 

He selects all the items after the first three. Then I tried this:

 li:nth-child(n+4):nth-child(-n+8) 

It only selects 4, 5 and 6, but I cannot repeat this pattern to select 10, 11 and 12. Is there a solution for this in CSS?

+7
source share
2 answers

This is a frequently asked question, but I would like to point out that the reason :nth-child(n+4):nth-child(-n+6) matches only one specific range of elements, so that it provides only one starting point (n + 4) and one endpoint (-n + 6). The only elements that can be greater than or equal to 4 and less than or equal to 6 are 4, 5, and 6, so it is not possible to combine elements outside this range using the same selector. Adding more aliases :nth-child() only limit matches.

The solution is to think about it in terms of columns, assuming that there will always be exactly 3 columns (elements) for each row. You have three columns, so you will need three separate aliases :nth-child() . Elements 4 and 10 from the first column are divided into 6 elements, so the argument to all the aliases :nth-child() should start with 6n.

The + b part in the An + B expression can be equal to +4, +5 and +6 or 0, -1 and -2 - they will coincide with the same set of elements:

  • li:nth-child(6n+4), li:nth-child(6n+5), li:nth-child(6n+6)
  • li:nth-child(6n), li:nth-child(6n-1), li:nth-child(6n-2)

You cannot do this with a single pseudo-class :nth-child() or one compound selector, consisting of any combination :nth-child() pseudos, because the An + B notation simply does not allow creating expressions that correspond to elements in ranges as described.

+9
source

You cannot do this with a single selector and you must use the nth-child selector grouping, as in the snippet below:

 li:nth-child(6n), li:nth-child(6n-1), li:nth-child(6n-2) { color: red; } 
 <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> <li>12</li> </ul> 

Selector Explanation:

  • li:nth-child(6n) - selects the elements of the 6th (= 6 * 1), 12th (= 6 * 2), 18th (= 6 * 3), etc.
  • li:nth-child(6n-1) - selects the elements of the 5th (= (6 * 1) -1), 11th (= (6 * 2) -1), 17th (= (6 * 3 ) -1) etc.
  • li:nth-child(6n-2) - selects the elements of the 4th (= (6 * 1) -2), 10th (= (6 * 2) -2), 16th (= (6 * 3 ) -2) etc.

Note: Normally n starts at 0, but I excluded it in the explanation because we do not have any 0th, -1st, or 2nd element.

+5
source

All Articles