One of the major problems that I have come up to in my coding career is on how to style children according to the number of it’s siblings. The solution comes from André Luís (discovered) & Lea Verou (refined):
The trick is to select the first child when it’s also the nth-from-the-last child. This effectively selects based on the number of siblings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* one item */ li:first-child:nth-last-child(1) { width: 100%; } /* two items */ li:first-child:nth-last-child(2), li:first-child:nth-last-child(2) ~ li { width: 50%; } /* three items */ li:first-child:nth-last-child(3), li:first-child:nth-last-child(3) ~ li { width: 33.3333%; } /* four items */ li:first-child:nth-last-child(4), li:first-child:nth-last-child(4) ~ li { width: 25%; } |
Stack overflow link: https://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has
Codepen example: https://codepen.io/kostas-krevatas/pen/ExoaWNK