Consider the following HTML structure:
<code class="html"><div class="foo"> <ul> <li>one</li> <li>two</li> </ul> <ul> <li>three</li> </ul> <ul> <li>four</li> </ul> </div></code>
The goal is to style the list items "one" and "three" in red. However, using the CSS selector:
<code class="css">.foo li:nth-child(1), .foo li:nth-child(3)</code>
styles the first child of each ul instead.
CSS-Only Approach:
Unfortunately, it is not possible to select nth-children across multiple parents using CSS alone. Neither :nth-child() nor sibling combinators allow for such selections.
Javascript or DOM Manipulation:
To achieve such targeting, you can resort to Javascript or DOM manipulation techniques. For instance, using jQuery:
<code class="javascript">$('.foo li:eq(0), .foo li:eq(2)').css('color', 'red');</code>
Class or ID Marking:
Alternatively, you can explicitly mark the target list items with classes or IDs. For example:
<code class="html"><div class="foo"> <ul> <li class="target">one</li> <li>two</li> </ul> <ul> <li class="target">three</li> </ul> <ul> <li>four</li> </ul> </div></code>
Then, style using the marked classes or IDs:
<code class="css">.foo .target { color: red; }</code>
The above is the detailed content of How to Target nth-child Across Multiple Parents in CSS?. For more information, please follow other related articles on the PHP Chinese website!