Home > Web Front-end > CSS Tutorial > How to Alternate Background Colors for '.parent' List Items With Intervening Non-'.parent' Elements?

How to Alternate Background Colors for '.parent' List Items With Intervening Non-'.parent' Elements?

Mary-Kate Olsen
Release: 2024-11-06 22:59:03
Original
765 people have browsed it

How to Alternate Background Colors for

Using :nth-child(even/odd) Selector with Class:

You want to apply alternating background colors to list items with the ".parent" class. However, the colors currently reset.

Problem:
The ".parent" elements are not behaving as expected due to the presence of non-".parent" elements within the list.

Solution:
Normally, the desired behavior cannot be achieved using only the :nth-child selector. However, you can employ the general sibling combinator (~):

  1. Select all odd ".parent" elements and apply the "green" color.
  2. For each non-".parent" element, toggle the colors of the following ".parent" elements using ~.

CSS Code:

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

/* After the first non-.parent, toggle colors */
li:not(.parent) ~ .parent:nth-child(odd) {
    background-color: red;
}
li:not(.parent) ~ .parent:nth-child(even) {
    background-color: green;
}

/* After the second non-.parent, toggle again */
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;
}
Copy after login

This approach alternates the colors for limited numbers of "excluded" non-".parent" elements, achieving the desired alternating pattern.

The above is the detailed content of How to Alternate Background Colors for '.parent' List Items With Intervening Non-'.parent' Elements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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