DEV Community

@kon_yu
@kon_yu

Posted on • Edited on

1

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

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;
}
Enter fullscreen mode Exit fullscreen mode

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>.
Enter fullscreen mode Exit fullscreen mode

! 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>.
Enter fullscreen mode Exit fullscreen mode

! 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>.
Enter fullscreen mode Exit fullscreen mode

image.png

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more