I recently saw a usage of structural pseudo-class selector on a foreign website. I thought it was very practical, so I tried it myself and recorded it:
This is the most basic style:
1
Contents in body:
1 <body> 2 <ul> 3 <li>第01个li> 4 <li>第02个li> 5 <li>第03个li> 6 <li>第04个li> 7 <li>第05个li> 8 <li>第06个li> 9 <li>第07个li> 10 <li>第08个li> 11 <li>第09个li> 12 <li>第10个li> 13 <li>第11个li> 14 ul> 15 body>
First is the usage of the most basic structural pseudo-class selector:
1 li:nth-child(8){ 2 background-color: #298EB2; 4 }
The results are displayed as:
Use:nth-child(n+6) which is equivalent to:nth-child(6) and above li tag elements:
1 li:nth-child(n+6){ 2 background-color: #298EB2; 4 }
The results are displayed as:
Similarly, use:nth-child(-n+6) which is equivalent to:nth-child(6) and the following li tag elements:
1 li:nth-child(-n+6){ 2 background-color: #298EB2; 4 }
The results are displayed as:
Based on the above principles we can come up with some advanced ones:
For example, you can use nth-child(n+4):nth-child(-n+8) to obtain the li tag elements of :nth-child(4) and above and :nth-child(8) and below:
1 li:nth-child(n+4):nth-child(-n+8){ 2 background-color: #298EB2; 3 }
The results are displayed as:
You can also use:nth-child(n+2):nth-child(odd):nth-child(-n+8) to get:nth-child(n+2) to:nth-child(-n+8 ) between singular li tag elements:
1 li:nth-child(n+2):nth-child(odd):nth-child(-n+8){ 2 background-color: #298EB2; 3 }
The results are displayed as:
Finally, we can also use:nth-child(3n+1) to get even li tag elements with numbers 1, 4, 7, and 10:
1 li:nth-child(3n+1):nth-child(even){ 2 background-color: #298EB2; 3 }
The results are displayed as: