Art & Algorithms

A blog about web design

Form validation


This CSS code styles invalid form input elements and their associated labels. Let’s break it down in detail:

1. Styling Invalid Inputs

input:user-invalid {
  border: 2px solid red;
  outline: 4px solid red;
}
  • input:user-invalid: This selector targets input elements that are in an invalid state, specifically when the user has interacted with them, triggering a validation error.

2. Styling Labels Containing Invalid Inputs

:has(input:user-invalid) label {
  color: red;
}
  • :has(input:user-invalid) label: This selector targets any label element that contains an input element in an invalid state.

3. Prepending an Icon to Labels with Invalid Inputs

label:has(+ input:user-invalid)::before {
  content: "✖";
  color: red;
}
  • label:has(+ input:user-invalid)::before: This selector targets label elements that are immediately followed by an input element in an invalid state and adds a pseudo-element before the label’s content.
  • content: "✖";: Inserts a red “✖” (cross mark) symbol before the label text, indicating an error.

Summary

  • The input:user-invalid selector applies red styling directly to invalid input elements, making them appear erroneous.
  • The :has selector is used to style parent label elements containing invalid inputs by changing the label’s text color to red.
  • Another :has The selector, combined with a pseudo-element, prepends a red “✖” symbol before labels associated with invalid inputs. This visually indicates which label is linked to the invalid input.

Leave a Reply

Your email address will not be published. Required fields are marked *