CSS :placeholder-shown

The :placeholder-shown pseudo-class represents any <input> or <textarea> element that is displaying placeholder text.

With this rule, we can do this type styling that would otherwise require the aid of JavaScript:

<input name=”food”…


This content originally appeared on DEV Community and was authored by Billy Coloe

The :placeholder-shown pseudo-class represents any <input> or <textarea> element that is displaying placeholder text.

With this rule, we can do this type styling that would otherwise require the aid of JavaScript:
placeholder-shown

<input name="food" placeholder=" " />
<label for="food">Favorite food</label>
const input = document.querySelector('input');

input.addEventListener('focus', () => {
  // Add parent class to move label above input
});

input.addEventListener('blur', () => {
  // Check if input has value
  // Remove parent class to reset label
});

But instead of all this overhead, we can leverage the :focus and :placeholder-shown CSS rules:

input:focus + label,
input:not(:placeholder-shown) + label {
  top: 14px;
  left: 6px;
  font-size: 12px;
  color: #fff;
}

Here we check if the input has focus OR if it does not have the placeholder shown (meaning there is a text value). If either of these states apply, we have the label float to the top left.

A hell of a lot easier than JS event handlers! ?

Here's a video using this in action:


CSS placeholder-shown

Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter and TikTok.


This content originally appeared on DEV Community and was authored by Billy Coloe


Print Share Comment Cite Upload Translate Updates
APA

Billy Coloe | Sciencx (2021-06-28T17:03:13+00:00) CSS :placeholder-shown. Retrieved from https://www.scien.cx/2021/06/28/css-placeholder-shown/

MLA
" » CSS :placeholder-shown." Billy Coloe | Sciencx - Monday June 28, 2021, https://www.scien.cx/2021/06/28/css-placeholder-shown/
HARVARD
Billy Coloe | Sciencx Monday June 28, 2021 » CSS :placeholder-shown., viewed ,<https://www.scien.cx/2021/06/28/css-placeholder-shown/>
VANCOUVER
Billy Coloe | Sciencx - » CSS :placeholder-shown. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/28/css-placeholder-shown/
CHICAGO
" » CSS :placeholder-shown." Billy Coloe | Sciencx - Accessed . https://www.scien.cx/2021/06/28/css-placeholder-shown/
IEEE
" » CSS :placeholder-shown." Billy Coloe | Sciencx [Online]. Available: https://www.scien.cx/2021/06/28/css-placeholder-shown/. [Accessed: ]
rf:citation
» CSS :placeholder-shown | Billy Coloe | Sciencx | https://www.scien.cx/2021/06/28/css-placeholder-shown/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.