Home >Web Front-end >CSS Tutorial >How Can I Detect Text Input in an HTML Input Field Using Only CSS?

How Can I Detect Text Input in an HTML Input Field Using Only CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 08:33:09481browse

How Can I Detect Text Input in an HTML Input Field Using Only CSS?

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!

Statement:
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