[TIL] CSS :empty isn’t applicable on form fields

Today I learned that the CSS :empty selector is implemented to look for child content (think of innerText/innerHTML).
This means it reports empty for filled form elements which are self-closing elements.

Findings

  • :empty reports empty for all form input elements because they have their values as attributes, not as inner content
  • :empty works for <textarea> elements depending on how they’re used in HTML
  • :blank is what we’d like to have but it’s not widely supported in browsers
  • :placeholder-shown as a workaround works for when there’s a placeholder attribute specified with a value (empty value doesn’t work)
  • :empty reports empty for <div>-elements that have a pseudo-element specified via ::after|::before { content: ''; } 🧐

I’ve created a Codepen with various tests that show the possibilities:

See the Pen CSS :empty pseudo-selector does not work well for form fields by Anselm Hannemann (@anselmh) on CodePen.

Sources:
Written on as Note