
How many elements your container has?
10/10/22About 2 minCSSArticle(s)blogcss-tip.comcss
How many elements your container has? 관련
CSS > Article(s)
Article(s)

How many elements your container has?
Detect the number of elements inside a container using :has() selector
Use the :has() selector and style your container based on its number of elements (direct children)
Note
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 How many elements it :has()? by 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 How many elements it :has()? by t_afif on CodePen.
More CSS Tips
- A rainbow gradient animation Use the new color interpolation to create an infinite rainbow gradient animation. January 31, 2023
- Card reveal animation A few mask trick to create a fancy reveal animation on hover. January 23, 2023
- An infinite image slider A minimal code to create an infinite image slider. September 16, 2022
- Cut the corners of your element Use CSS mask to cut the four corners of an element with a circular shapes. September 08, 2022

How many elements your container has?
Detect the number of elements inside a container using :has() selector