Detecting Text Input Using CSS
A common requirement arises when customizing web pages using CSS: the ability to detect if an input field contains text. Surprisingly, this functionality is not directly provided by CSS.
Attempted Solutions
Various approaches have been unsuccessful, including using the :empty pseudo-class and checking for empty values [value=""].
CSS Placeholder Approach
However, if the input field has a placeholder attribute, CSS offers a solution: the :placeholder-shown pseudo class. This class can be used to distinguish between an empty input field and one with a placeholder.
Implementation
The key is to ensure that the placeholder attribute is present and contains a non-blank value, even if it's just a single space. Here's an example:
input:not(:placeholder-shown) { border-color: green; } input:placeholder-shown { border-color: red; }
Conclusion
Utilizing the :placeholder-shown pseudo class, you can effectively detect whether an input field contains text, even on pages where you have no control.
The above is the detailed content of How Can I Detect Text Input in an HTML Input Field Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!