Count child elements in parent

17 February 2022 JavaScript Web Development CSS

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.

The key part is the following

    li:first-child:nth-last-child(2),
    li:first-child:nth-last-child(2) ~ li {
        width: 50%;
        background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
    }

See the Pen Styling elements based on number of siblings by r4nd3l (@r4nd3l) on CodePen.