Home > Web Front-end > CSS Tutorial > How Can I Style Input Fields Based on Whether They Contain Text Using Only CSS?

How Can I Style Input Fields Based on Whether They Contain Text Using Only CSS?

Mary-Kate Olsen
Release: 2024-12-15 22:14:14
Original
449 people have browsed it

How Can I Style Input Fields Based on Whether They Contain Text Using Only CSS?

Identifying Text in Input Fields Without JavaScript

In the realm of CSS styling, detecting the presence of text within an input element can be a perplexing task. However, the elusive :empty pseudo-class and [value=""] selector fail to yield the desired results.

Nonetheless, the :placeholder-shown pseudo class emerges as a potential solution. This pseudo-class targets input elements that have a placeholder attribute without displaying the placeholder text.

How to Use :placeholder-shown

  1. Ensure that your input element has a non-empty placeholder attribute. Even a single space is acceptable.
  2. Use the :not(:placeholder-shown) selector to style the input when it contains text.
  3. Use the :placeholder-shown selector to style the input when it's empty.

For example:

input:not(:placeholder-shown) {
  border-color: green;
}

input:placeholder-shown {
  border-color: red;
}
Copy after login

This code would color the input green when it contains text and red when it's empty.

Caveats

Note that this technique relies on the use of placeholder attributes. As such, it may not be suitable for scenarios where placeholder text is not desired.

The above is the detailed content of How Can I Style Input Fields Based on Whether They Contain Text Using Only 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