CSS :has() Examples

Style a label or fieldset and hide / show an error message based on the validation status of it's input.

Try typing a string or negative number into these number inputs (tab to blur the input).

label:has(input:user-valid) {
  color: #000;
  background: #beff00;
}

label:has(input:user-invalid) {
  background: #ff474e;
}

fieldset:has(input:user-valid) {
  border-left: 10px solid #beff00;
}

fieldset:has(input:user-invalid) {
  border-left: 10px solid #ff474e;
}

label:has(input:user-valid) ~ .success,
fieldset:has(input:user-valid) .success {
  display: block;
}

label:has(input:user-invalid) ~ .error,
fieldset:has(input:user-invalid) .error {
  display: block;
}

Label Example:

Quantity is valid!

Invalid quantity.


Fieldset Example:

Amount is valid!

Invalid amount.