loading...

Organizing the behavior of even and odd in :nth-child

konyu profile image @kon_yu Updated on ・2 min read

Beginning

It is useful to decorate even- and odd-numbered elements when writing HTML, so I organized the behavior of :nth-child(even) and :nth-child(odd).

main point

CSS to use for display

The color of the letters is blue, and if it is an even number, it is red.

.list {
  color: blue;
}

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

.list2 {
  color: aqua;
}

First, the basics of writing.

Even elements are counted from 0 to red in the character color

<ul>
  <li class='list'>0</li>
  <li class='list'>1</li>
  <li class='list'>2</li>
  <li class='list'>3</li>
</ul>.

! image.png

The tags are the same but the classes are different

The number of siblings remains the same even if the first element is of a different class, so .list:nth-child(even) is applied to the second element

<ul>
  <li class='list2'>0</li>
  <li class='list'>1</li>
  <li class='list'>2</li>
  <li class='list'>3</li>
</ul>.

! image.png

with another tag in between

We only see sibling elements with the same tag. If you put another tag between them, the even and odd count will be reset.

<ul>
  <li class='list'>0</li>
  <p>In-between elements</p>.
  <li class='list'>1</li>
  <li class='list'>2</li>
  <li class='list'>3</li>
</ul>.

image.png

Here is the sample code for this time
https://jsfiddle.net/kon_yu/9p8qzbjc/13/

Discussion

pic
Editor guide