Styling parent elements based on the number of children with CSS :has()

PHOTO EMBED

Fri Nov 25 2022 23:56:41 GMT+0000 (Coordinated Universal Time)

Saved by @danlourenco #css

/* At most 3 (3 or less, excluding 0) children */
ul:has(> :nth-child(-n+3):last-child) {
	outline: 1px solid red;
}

/* At most 3 (3 or less, including 0) children */
ul:not(:has(> :nth-child(3))) {
	outline: 1px solid red;
}

/* Exactly 5 children */
ul:has(> :nth-child(5):last-child) {
	outline: 2px solid blue;
}

/* At least 10 (10 or more) children */
ul:has(> :nth-child(10)) {
	outline: 2px solid green;
}

/* Between 7 and 9 children (boundaries inclusive) */
ul:has(> :nth-child(7)):has(> :nth-child(-n+9):last-child) {
	outline: 2px solid yellow;
}


/* Non-demo styles below */
@layer base {
	@layer layout {
		html {
			max-width: 84ch;
			padding: 3rem 2rem;
			margin: auto;
			line-height: 1.5;
			font-size: 1.25rem;
		}
		body {
			margin: 0;
			padding: 0;
		}
		a,
		a:visited {
			color: blue;
		}
		
		h2 {
			margin-top: 2em;
		}
	}
	
	@layer code {
		pre {
			border: 1px solid #dedede;
			padding: 1em;
			background: #f7f7f7;
			font-family: "Courier 10 Pitch", Courier, monospace;
			overflow-x: auto;
			border-left: 0.4em solid cornflowerblue;
			tab-size: 4;
		}
	}

	@layer support {
		.no-support,
		.has-support {
			margin: 1em 0;
			padding: 1em;
			border: 1px solid #ccc;
		}

		.no-support {
			background-color: #ff00002b;
			display: block;
		}
		.has-support {
			background-color: #00ff002b;
			display: none;
		}
		:is(.has-support, .no-support) > :first-child {
			margin-top: 0;
		}
		:is(.has-support, .no-support) > :last-child {
			margin-bottom: 0;
		}

		@supports(selector(:has(*))) {
			.no-support[data-support="css-has"] {
				display: none;
			}
			.has-support[data-support="css-has"] {
				display: block;
			}
		}
	}
}

@layer reset {
	
}
content_copyCOPY

https://codepen.io/bramus/pen/bGKoZNq