Home  >  Article  >  Web Front-end  >  How to Target nth-child Across Multiple Parents in CSS?

How to Target nth-child Across Multiple Parents in CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 22:01:02402browse

How to Target nth-child Across Multiple Parents in CSS?

CSS: Targeting nth-child Across Multiple Parents

Problem

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.

Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn