Skip to main content
CSS Tip

How many elements your container has?

Use the :has() selector and style your container based on its number of elements (direct children)

⚠️ It doesn't count text nodes. Only tags!

.container:not(:has(*)) { /* 0 elements */}
.container:has(> :last-child:nth-child(1)) { /* 1 element */}
.container:has(> :last-child:nth-child(2)) { /* 2 elements */}
.container:has(> :last-child:nth-child(3)) { /* 3 elements */}
/*.container:has(> :last-child:nth-child(N)) { /* N elements */}*/

See the Pen How many elements it :has()? by Temani Afif (@t_afif) on CodePen.