Styling Empty Input Fields with CSS
One common styling need is to apply specific rules to empty input fields. This can be useful for providing visual cues to users, such as a placeholder text or a colored border. However, using the input[value=""] selector to target empty inputs may not work as intended.
In modern browsers, the :placeholder-shown pseudo-class provides a more reliable way to style empty input fields. This pseudo-class targets input fields where the placeholder text is currently visible, indicating that the input field is empty.
To apply a red border to an empty input field, you can use the following CSS:
input:placeholder-shown { border: 1px solid red; }
Note that you must also set a placeholder attribute on the input field in HTML:
<input type="text" placeholder=" "> <!-- Do not remove placeholder -->
Chrome requires at least a space character as the placeholder value to trigger the :placeholder-shown pseudo-class. This ensures that the input field is technically not empty while still allowing for user input.
By using :placeholder-shown, you can create custom styling that targets empty input fields and provides enhanced user feedback.
The above is the detailed content of How Can I Reliably Style Empty Input Fields with CSS?. For more information, please follow other related articles on the PHP Chinese website!