[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.
Update 20. Feb 2023
Browser vendors agreed to implement :user-invalid
and :user-valid
selectors into browsers this year as part of the Web Interoperability goals.
Sources:
- https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
The one we’re talking about - https://developer.mozilla.org/en-US/docs/Web/CSS/:blank
Unfortunately, nearly no browser supports it, unfortunately - https://stackoverflow.com/questions/3617020/matching-an-empty-input-box-using-css
Some ideas how to work around this limitation - https://zellwk.com/blog/check-empty-input-css/
The best guide using browser validation methods as a hack, but you’re still lost when you want to avoid using the native validation.