My goal is to create a form where the label of the input field moves up when the user starts typing, and stays up if they enter any text. However, if the user leaves the input area blank, the label should revert back to its original position.
I have tried implementing this functionality with an input box that has the "required" attribute, and it works as expected. But when I apply the same concept to an input field without the required attribute and enter some content, the label moves back down instead of staying up.
div{
margin-top:40px;
}
.btn-add input[type="text"]{
width: 90%;
padding: 10px 20px 0 20px;
border: none;
border-bottom:1px solid #999;
font-size: 140%;
color: #000;
}
.btn-add input:focus ~ .floating-label{
top: -20px;
bottom: 10px;
left: 10px;
font-size: 20px;
opacity: 1;
color: rgb(100, 6, 6);
}
.floating-label {
position: absolute;
pointer-events: none;
left: 20px;
top:10px;
transition: 0.2s ease all;
color: #999999;
font-size: 120%;
}
.form-float{
position: relative;
}
<div class="form-float btn-add">
<input type="text" class="inputText" placeholder="" >
<label class="floating-label" >Button text</label>
</div>
To overcome this issue, I removed
input:not(:focus):valid~.floating-label
so that it can work properly even with non-required fields.