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.

You can also have range selection

.container:has(> :nth-child(3)) { /* 3 elements or more */ }
/* .container:has(> :nth-child(X)) : X elements or more */

.container:has(> :last-child:nth-child(-n + 3)) { /* between 1 and 3 elements */}
/* .container:has(> :last-child:nth-child(-n + X)): between 1 and X elements */

.container:has(> :nth-last-child(3):nth-child(-n + 3)) { /* between 3 and 5 elements */}
/* .container:has(> :nth-last-child(X):nth-child(-n + (Y - X + 1))): between X and Y elements */

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