Home  >  Article  >  Web Front-end  >  How to Toggle Colors with :nth-child(even/odd) Selectors When Non-Parent Elements Exist?

How to Toggle Colors with :nth-child(even/odd) Selectors When Non-Parent Elements Exist?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 04:22:14273browse

How to Toggle Colors with :nth-child(even/odd) Selectors When Non-Parent Elements Exist?

nth-child(even/odd) Selector with Class Issue

When implementing :nth-child(odd/even) selectors for a class-based list, it's common to encounter color resetting issues. In the provided example, elements were meant to inherit the colors of the text, but they were resetting instead.

This issue arises because:nth-child(even/odd) selectors inherently target all child elements, regardless of class or other attributes. To address this problem, the ~ general sibling combinator can be employed.

The concept involves toggling the colors of subsequent .parent elements after encountering non-.parent elements. Here's a breakdown of the CSS:

/* Initial even/odd coloring */
.parent:nth-child(odd) {
    background-color: green;
}

.parent:nth-child(even) {
    background-color: red;
}

/* Toggle colors after first non-.parent */
li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: red;
}

li:not(.parent) ~ .parent:nth-child(even) {
    background-color: green;
}

/* Toggle colors after second non-.parent */
li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: green;
}

li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(even) {
    background-color: red;
}

This solution allows for toggling between colors even when non-.parent elements are present. However, it's crucial to note that this approach has limitations and should only be used for a limited number of excluded elements.

By implementing this strategy, you can effectively apply :nth-child(odd/even) selectors to class-based lists and achieve the desired alternating color scheme, ensuring that the list items inherit the colors of their text content.

The above is the detailed content of How to Toggle Colors with :nth-child(even/odd) Selectors When Non-Parent Elements Exist?. 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