Styling Nested nth-child Elements across Multiple Parents
Seeking a solution to style specific nested elements within varying parent structures, consider the following markup:
The goal is to apply styles to "one" and "three," regardless of whether they are the first children of each
Limitation of :nth-child()
Attempts to use :nth-child() fall short because it only applies to elements that share the same parent. In this scenario, the CSS selector .foo li:nth-child(1), .foo li:nth-child(3) would only target the first children of each
Alternative Solutions
JavaScript:
Using a library like jQuery allows you to select elements using JavaScript's powerful filtering capabilities. For instance, the following script would target the first and third
$('.foo li:eq(0), .foo li:eq(2)')
Explicit Element Marking:
You can explicitly mark the desired elements with classes or IDs to enable their selection via CSS. For example, adding classes to the first and third
Then, you can use CSS to target the marked elements:
.foo .first,
.foo .third {
color: red;
}
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