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

DDD
Release: 2024-10-24 00:09:29
Original
187 people have browsed it

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:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
    </ul>
    <ul>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>
Copy after login

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

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

Then, style them using the newly added classes:

.foo li.first,
.foo li.third
{
    color: red;
}
Copy after login

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!

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
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!