All examples

Building blocks > Has
Form feedback with :has()

With input:valid you can style inputs that are valid.

There is also input:invalid, that styles input that have content that does not meet the requirements.

Exercise: using :has() selectors, make it so that:

(change .invalid/.valid to selectors that do this)

Example code

							<div class="field">
	<label for="name">Name</label>
	<input id="name" type="text">
</div>
<div class="field">
	<label for="email">Email</label>
	<input id="email" type="email" required>
	<small>Please enter a valid email.</small>
</div>

<style>
.field {
	padding: 1rem;
	margin-bottom: 1em;
	border: 2px solid #ddd;
	border-radius: 0.5rem;
}
.field small {
	display: none;
}

.invalid small {
	display: block;
	color: #dc2626;
}

.invalid {
	border-color: #dc2626;
	background: #fff5f5;
}

.valid {
	border-color: #16a34a;
	background: #f0fff4;
}

</style>
						

Preview

Show answer

Example code

							<div class="field">
	<label for="name">Name</label>
	<input id="name" type="text">
</div>
<div class="field">
	<label for="email">Email</label>
	<input id="email" type="email" required>
	<small>Please enter a valid email.</small>
</div>

<style>
.field {
	padding: 1rem;
	margin-bottom: 1em;
	border: 2px solid #ddd;
	border-radius: 0.5rem;
}

.field:has(input:invalid) {
	border-color: #dc2626;
	background: #fff5f5;
}

.field:has(input:valid) {
	border-color: #16a34a;
	background: #f0fff4;
}

.field small {
	display: none;
}

.field:has(input:invalid) small {
	display: block;
	color: #dc2626;
}
</style>
						

Preview