3

I have a input element with a placeholder which should appear always

.wrapper {
  position: relative;
}

input {
  font-size: 14px;
  height: 40px;
}

.placeholder {
  position: absolute;
  font-size: 16px;
  pointer-events: none;
  left: 1px;
  top: 2px;
  transition: 0.1s ease all;
}

input:focus~.placeholder {
  top: -1px;
  font-size: 11px;
}

input[value=""]~.placeholder {
  top: -1px;
  font-size: 11px;
}
<div class="wrapper">
  <input type="text">
  <span class="placeholder">E-Mail</span>
</div>

And I want the pseudo placeholder to remain small if there is any text in the input field. There must be something wrong with the input[value=""] ~ .placeholder selector but I have no idea.

Carl Binalla
  • 5,393
  • 5
  • 27
  • 46
Impostor
  • 2,080
  • 22
  • 43
  • 1
    Possible duplicate of [Detect if an input has text in it using CSS -- on a page I am visiting and do not control?](https://stackoverflow.com/questions/16952526/detect-if-an-input-has-text-in-it-using-css-on-a-page-i-am-visiting-and-do-no) – Carl Binalla Oct 10 '19 at 11:00

2 Answers2

3

Use :placeholder-shown but you will need to have at least an empty placeholder

.wrapper{
  position: relative;
}

input {
  font-size: 14px;
  height: 40px;
}

.placeholder {
  position: absolute;
  font-size:16px;
  pointer-events: none;
  left: 1px;
  top: 2px;
  transition: 0.1s ease all;
}

input:focus ~ .placeholder{
  top: -1px;
  font-size: 11px;
}

input:not(:placeholder-shown) ~ .placeholder{
  top: -1px;
  font-size: 11px;
}
<div class="wrapper">
  <input type="text" placeholder=" ">
  <span class="placeholder">E-Mail</span>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • ah I checked for value but there should be NO value - how about `input:not([value])` instead to avoid this placeholder attribute? – Impostor Oct 10 '19 at 11:04
  • 2
    @Dr.Snail this won't work, at the CSS level you don't know if it has a value or not. You can only know if the *value* attribute is specified or not. This selector will not select input with value attribute. – Temani Afif Oct 10 '19 at 11:05
  • Just learning about `placeholder=" "` now; what a trick I wish it was stated in the MDN docs. Thank you! – Jessy Jun 27 '23 at 13:54
1

You won't be able to catch this with the value attribute as it will only apply the value on page load. Either you use the placeholder-shown as Temani Afif answered, or if you want to support edge as well, you can use a :valid selector on a required field

.wrapper {
  position: relative;
}

input {
  font-size: 14px;
  height: 40px;
}

.placeholder {
  position: absolute;
  font-size: 16px;
  pointer-events: none;
  left: 1px;
  top: 2px;
  transition: 0.1s ease all;
}

input:focus~.placeholder {
  top: -1px;
  font-size: 11px;
}

input:valid~.placeholder {
  top: -1px;
  font-size: 11px;
}
<div class="wrapper">
  <input type="text" required>
  <span class="placeholder">E-Mail</span>
</div>
Joschi
  • 2,874
  • 1
  • 18
  • 23