animuson animuson - 3 months ago 58
CSS Question

:not(:empty) CSS selector is not working?

I'm having a heck of a time with this particular CSS selector which does not want to work when I add

to it. It seems to work fine with any combination of the other selectors:

input:not(:empty):not(:focus):invalid { border-color: #A22; box-shadow: none }

If I remove the
part, it works just fine. Even if I change the selector to
it still won't select input fields which have text typed into them. Is this broken or am I just not allowed to use
within a

The only other thing I can think of is that browsers are still saying that the element is empty because it has no children, just a "value" per say. Does the
selector not have separate functionality for an input element versus a regular element? This doesn't seem probable though because using
on a field and typing something into it will cause the alternate effects to go away (because it is no longer empty).

Tested in Firefox 8 and Chrome.


<input> elements are considered empty elements (or void elements) by the HTML definition of "empty". So they will always match the :empty pseudo-class, whether or not they have a value.

Also, from the Selectors spec:

The :empty pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness;

And finally, while value is a DOM property of form input elements, it's not a child in terms of the document tree, unlike text nodes, so it doesn't affect emptiness.

Consequently, input:not(:empty) will never select anything in a proper HTML document.

I don't think you can style empty <input> fields dynamically using just CSS (i.e. rules that apply whenever a field is empty, and don't once text is entered). You can select initially empty fields if they have an empty value attribute (input[value=""]) or lack the attribute altogether (input:not([value])), but that's about it.