My challenge involves creating a floating label for a styled input using only CSS. The issue arises when I realize that this implementation requires the input to have the required
attribute in order for the label to function properly (using pure CSS). Is there a way to achieve this without having to use the required
attribute, as its presence is causing complications with form validations? Below is a snippet of my HTML markup and CSS styling:
.myInput {
position: relative;
input {
padding: 30px 10px 10px;
display: block;
width: 100%;
border: 1px solid black;
&:focus {
outline: none;
}
&:focus~label,
&:valid~label,
&:placeholder-shown~label {
top: 10px;
color: black;
}
}
label {
color: red;
position: absolute;
pointer-events: none;
left: 10px;
top: 20px;
transition: 0.2s ease all;
-moz-transition: 0.2s ease all;
-webkit-transition: 0.2s ease all;
}
}
<div class="myInput">
<input type="text" required id="target" />
<label htmlFor="target">
label
</label>
</div>
Upon removing the required
attribute from the input field, the label no longer transitions into the placeholder spot when the input is empty. Here's a link to a demonstration on JSFiddle - https://jsfiddle.net/1ob2npcu/2/
I am exploring possibilities to accomplish this purely through CSS – I am utilizing SCSS for this task. Any insights or solutions would be greatly appreciated. Thank you!