Use :first-child and :nth-last-child to determine the number of child elements

When reading "The Secret of CSS", I found the magical effect of the selector, which can determine the number of child elements, such as:

li:first-child:nth-last-child(2),li:first-child:nth-last-child(2)~li {
  background-color:pink;
}

This applies if the first child element is liand the parent element has 2 children, then both the first liand subsequent ones liwill apply, and neither will apply if there are more or less child elements.

Think carefully about the core logic:

  • first-child:nth-last-child(2)=> that is the first and the second from the bottom => a total of two child elements

Use selectors to further expand:

  • first-child:nth-last-child(n+2)=> It is the first one, and it is the second, 3, 4,,,,, etc. => The number of child elements> 2
  • first-child:nth-last-child(-n+4)=> that is the first one, and the last one, 2, 3, 4 => the number of child elements <= 4
  • first-child:nth-last-child(-n+4):nth-last-child(n+2)=> That is, the first one, and the second, 3, 4,,,, and the penultimate 1, 2, 3, and 4 => the number of child elements [2, 4]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325600688&siteId=291194637