Home > Web Front-end > CSS Tutorial > How Can I Reliably Style Empty Input Fields with CSS?

How Can I Reliably Style Empty Input Fields with CSS?

Linda Hamilton
Release: 2024-12-14 05:24:10
Original
428 people have browsed it

How Can I Reliably Style Empty Input Fields with CSS?

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;
}
Copy after login

Note that you must also set a placeholder attribute on the input field in HTML:

<input type="text" placeholder=" "> <!-- Do not remove placeholder -->
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template