6

CSS :placeholder-shown

 3 years ago
source link: https://dev.to/cilly_boloe/css-placeholder-shown-5848
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for CSS :placeholder-shown

CSS :placeholder-shown

Jun 28

・1 min read

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

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

<input name="food" placeholder=" " />
<label for="food">Favorite food</label>
Enter fullscreen modeExit fullscreen mode
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
});
Enter fullscreen modeExit fullscreen mode

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;
}
Enter fullscreen modeExit fullscreen mode

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:


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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK