brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: :placeholder-shown in CSS builds a floating label without JavaScript

Css
~/tips/tip-css-placeholder-shown-floating-label

.field label {

The label moves up out of the way once a field has a value or focus.

A floating label needs to know whether the field is empty. CSS cannot read the value, but it can see whether the placeholder is showing, and that is enough.

<div class="field">
  <input id="email" type="email" placeholder=" ">
  <label for="email">Email address</label>
</div>

.field { position: relative; }
.field label {
  position: absolute; left: 0.75rem; top: 0.9rem;
  transition: translate 0.15s, scale 0.15s;
}
.field input:focus + label,
.field input:not(:placeholder-shown) + label {
  translate: 0 -1.4rem;
  scale: 0.85;
}

:placeholder-shown matches an input or textarea while it is showing its placeholder, which means while it is empty. The trick is a placeholder of a single space: invisible, but present, so the selector has something to work with. With :not() in front you get “this field has content”.

I put the label after the input in the markup so the + combinator can reach it. With :has() you could put it first, if you prefer that order.

The selector works in every current browser. The caveat is that it only works when the placeholder attribute exists, so a field without one never matches. Also keep the real label: the placeholder trick is styling, and screen readers still need the label.

Further reading: MDN: :placeholder-shown

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link