Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating label not working when required attribute removed

Tags:

html

css

I have done a floating label to my input filed like below. And it's working fine as well. But when I remove that required field of input,the floating label is not working (though I don't need the required filed). Please suggest some ways to solve this issue.

input:focus~.floating-label,
input:not(:focus):valid~.floating-label {
  top: 6px;
  bottom: 12px;
  left: 20px;
  font-size: 11px;
  opacity: 1;
}

.floating-label {
  position: absolute;
  pointer-events: none;
  left: 20px;
  top: 18px;
  text-transform: uppercase;
  transition: 0.2s ease all;
  color: #b2b2b2;
}
<input type="text" id="floating_name" value="" required/>
<span class="floating-label">Enter</span>
like image 562
temp Avatar asked Jun 11 '17 04:06

temp


2 Answers

Please try this another method which can be done without 'required' attribute

use ':placeholder-shown'

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

so there are 2 cases for label to be floated

  • when placeholder not visible (that is when there is data in field)
  • when the field is focused

and 1 case for label not to be floated

  • when placeholder is visible ( that is when no data in field)

fiddle : floating label demo

.form-group {
  position: relative;
  margin-bottom: 1.5rem;
}
input:placeholder-shown + .form-control-placeholder{
  margin-top:0%;
}

input + .form-control-placeholder ,
.form-control:focus + .form-control-placeholder{
  position: absolute;
  transition: all 200ms;
  margin-left:-25%;
  margin-top:-3%;
}
<br><br>
<div class="form-group">
  <input type="text" id="name" class="form-control" placeholder=" " >
  <label class="form-control-placeholder" for="name">Name</label>
</div>
like image 51
Prajeesh PR Avatar answered Oct 04 '22 14:10

Prajeesh PR


try this. Using input:not(:placeholder-shown) should definitly work:

input:focus ~ .floating-label,
input:not(:placeholder-shown) ~ .floating-label{
  top: 8px;
  bottom: 10px;
  left: 20px;
  font-size: 11px;
  opacity: 1;
}

.inputText {
  font-size: 14px;
  width: 200px;
  height: 35px;
}

.floating-label {
  position: absolute;
  pointer-events: none;
  left: 20px;
  top: 18px;
  transition: 0.2s ease all;
}
<div>
  <input placeholder="" type="text" class="inputText" />
  <span class="floating-label">Your email address</span>
</div>
like image 35
adebiyij Avatar answered Oct 04 '22 14:10

adebiyij