Floating label not working when required attribute removed
Selector
input:focus
selects input when it get focus and Selectorinput:not(:focus):valid
selects input ifvalid input
not be focus.A. when you use
required attribute
and Do not enter any value in it:1)Before focus and when lose focus:Nothing not be selected.(original state)
2)after focus input is invalid and it is selected with
input:focus
.B. when you remove
required
attribute:1)before focus select with
input:not(:focus):valid
.2)after focus select with
input:focus
.So, input is selected forever , And
.floating-label
will not return to the original state.
in your question, you say:"I don't need the required filed"
So, remove
input:not(:focus):valid~.floating-label
.
Full Code:
input:focus ~ .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="">
<span class="floating-label">Enter</span>
The :valid
selector only works for form elements with limitations. When you remove required
part of your CSS no longer applies. I removed input:not(:focus):valid ~ .floating-label
and it works again.
input:focus~.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="" />
<span class="floating-label">Enter</span>
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>