CSS ::placeholder and :placeholder-shown

Suprabha - May 25 '21 - - Dev Community

The `:placeholder-shown` CSS pseudo-class represents any `` or `` element that is currently displaying placeholder text.

<input type="text" placeholder="some text" />
Enter fullscreen mode Exit fullscreen mode
input:placeholder-shown {
  font-family: "Baloo 2", cursive;
  font-weight: bold;
  background-color: pink;
}
Enter fullscreen mode Exit fullscreen mode

Output:

placeholder shown

In above snippet,

  1. If user has not typed anything then placeholder shown background color will be pink
  2. When user has typed something then there will be no placeholder shown and the background color will be transparent

πŸ“ NOTE: :placeholder-shown won't work if there will be no placeholder text

πŸ—“ Example:

<input type="text" />
Enter fullscreen mode Exit fullscreen mode
input:placeholder-shown {
  background-color: pink;
}
Enter fullscreen mode Exit fullscreen mode

❌ The above snippet doesn't work

:placeholder-shown vs ::placeholder πŸ”₯

We can use :placeholder-shown to style the input element.

input:placeholder-shown {
  border: 1px solid pink;
  background: yellow;
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

Here, we set color: blue, but it didn't work. That's because :placeholder-shown will only target the input itself. But for the actual placeholder text, you have to use the pseudo-element ::placeholder.

::placeholder pseudo-element can be used to style the placeholder text in <input> or <textarea> element.

input::placeholder {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

Output:

placeholder

If you wanted to add styles for empty placeholder, we can pass empty string " " as placeholder.

<input type="text" placeholder=" " />
Enter fullscreen mode Exit fullscreen mode

Output:

placeholder shown

Now, why don't we combine two selector :not and :placeholder-shown.
So we can target if the input is not empty then we can apply css.

<input placeholder="some text" value="Check with empty!" />
Enter fullscreen mode Exit fullscreen mode
input:not(:placeholder-shown) {
  background-color: pink;
}
Enter fullscreen mode Exit fullscreen mode

Output:

placeholder not shown

In above snippet,

  1. If the input has value then the background-color will get applied
  2. If the input is empty then background-color not applies

πŸ“ NOTE: ::placeholder does not work with :not selector.

Reference 🧐

🌟 Twitter πŸ‘©πŸ»β€πŸ’» suprabha.me 🌟 Instagram
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player