nth-child ninja power

In this article, I will share a small example of the :nth-child() pseudo-class usage that allows one to efficiently work with dynamic lists.

Problem

Let’s first look at the problem I had. My task was to render a tree with different types of nodes. One of the node types presents a list, and I wanted to add alternating zebra-like backgrounds to them. Below is the visual representation of the UI I’ve been aiming for.

Tree fragment diagram

Ok, it seems that I should use a common pattern to match even nodes with an offset – 2n + 4 works for this example.

However, the difficulty is that this list of nodes is dynamic and the nodes can be different. For instance, not every node has a description, and, in this case, offset changes. If a user has permission to edit nodes, there will be an additional node after the description to select all node items for bulk editing. All of this makes offset of node items unpredictable.

According to its definition the pseudo-class :nth-child() matches elements based on the indexes of the elements in the child list of their parents. It means that the selector .nodeItem:nth-child(even) will not work as might be expected. It will highlight only .nodeItem nodes but analyse whether the element is even or not among all siblings.

:nth-child(even) applied in the lists with different structure

Solution

:nth-child() has syntax to match selectors though. The :nth-child() argument can not only describe the function to calculate indices but also restrict them by any selector. For the node example, it looks the following way:

.nodeItem:nth-child(even of .nodeItem) {}
Enter fullscreen mode
Exit fullscreen mode

Now it truly scans only .nodeItem nodes and applies styles to even nodes among them!

:nth-child(even of) applied in the lists with different structure

While it is very useful major browsers have supported this syntax only since the spring of 2023 so please still be careful and consider JavaScript solutions if you need to apply a similar approach to styling your dynamic lists with support for older browsers.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Free 2025 jamb questions and answers science pdf / jamb 2025 answers science pdf.