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

Barbara Streisand
Release: 2024-10-23 22:01:02
Original
401 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

Then, style using the marked classes or IDs:

<code class="css">.foo .target {
  color: red;
}</code>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!