Floating label for Bootstrap 4
Example: https://codesandbox.io/s/github/tkrotoff/bootstrap-floating-label/tree/codesandbox.io
- Small: less than 200 lines of SCSS
- Works in latest Chrome/Chromium, Firefox and Safari
- Lower support in IE11 and Edge (see
:placeholder-shown
not supported and Can I use placeholder-shown?) - Works with any font family and size
- Uses Bootstrap variables: nothing hardcoded
The Nielsen Norman Group talks about "Placeholders and Floating Labels disadvantages"
npm install @tkrotoff/bootstrap-floating-label
Import bootstrap4-floating-label.scss
@import '~@tkrotoff/bootstrap-floating-label/src/bootstrap4-floating-label';
Place <label>
under <input>
inside your Bootstrap 4 code:
<div class="floating-label">
<input type="email" id="email" class="form-control" placeholder="name@example.com">
<label for="email">Email</label>
</div>
There is no good way to detect if the user entered text inside an input using CSS.
With React, the CSS works in most cases because React populates the value
attribute.
If you are not using React, you should have a "space placeholder" (<input placeholder=" ">
, see https://codepen.io/tkrotoff/pen/KjgyZj) otherwise the label will be above the input instead of inside.
You should also have a "space placeholder" with React and <input type="number">
.
Because when the user enters something different than a number, the HTMLInputElement.value
property is empty (and ValidityState.badInput
is true), see https://codepen.io/tkrotoff/pen/RLQQqo.