"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Style Specific nth-Children Across Multiple Parents in CSS

How to Style Specific nth-Children Across Multiple Parents in CSS

Published on 2024-11-09
Browse:485

How to Style Specific nth-Children Across Multiple Parents in CSS

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:

  • one
  • two
  • three
  • four

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:

  • JavaScript: Libraries like jQuery make it easy to manipulate DOM elements and select specific ones, such as $('.foo li:eq(0), .foo li:eq(2)').
  • Explicit Markup: Add classes or IDs to the first and third li elements explicitly, such as:
  • one
  • two
  • three
  • four

Then, style them using the newly added classes:

.foo li.first,
.foo li.third
{
    color: red;
}
Release Statement This article is reprinted at: 1729684246 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3