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.
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.
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) {}
Now it truly scans only .nodeItem
nodes and applies styles to even nodes among them!
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.