Styling Specific nth-Children Across Multiple Parents
When styling nested elements using the nth-child selector, it's crucial to note that the selector operates within a single parent context. This can lead to challenges when targeting specific child elements across multiple parents.
The Issue:
Consider the following markup:
<div class="foo"> <ul> <li>one</li> <li>two</li> </ul> <ul> <li>three</li> </ul> <ul> <li>four</li> </ul> </div>
The goal is to style the first and third li elements within .foo. Using the following CSS:
.foo li:nth-child(1), .foo li:nth-child(3) { color: red; }
This approach won't work because nth-child selects the first and third child of each ul.
The Solution:
Using CSS alone, it's not possible to target nth-children across multiple parents. However, there are alternative solutions:
<div class="foo"> <ul> <li class="first">one</li> <li>two</li> </ul> <ul> <li class="third">three</li> </ul> <ul> <li>four</li> </ul> </div>
Then, style them using the newly added classes:
.foo li.first, .foo li.third { color: red; }
The above is the detailed content of How to Style Specific nth-Children Across Multiple Parents in CSS. For more information, please follow other related articles on the PHP Chinese website!