I have a floating label for a styled input done with all CSS. The problem I am having is that this requires the input to have the required
property in order to manage the moving label ( with pure CSS). I am wondering if it's possible to do this without the required
field because putting this in certain forms is messing with the form validations. My markup and CSS looks like so :
.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>
You'll notice that if you remove the required
the label no longer moves into the placeholder spot in an empty input. Here it is in a working fiddle - https://jsfiddle.net/1ob2npcu/2/
I am trying to see if there is a way to do this purely in CSS - i am using SCSS if this helps. Thanks!
If you remove the required
attribute then also remove
&:valid~label
from the CSS
: then you need to define a placeholder for the input and revert the logic for the placeholder-shown
pseudoclass, so the SCSS style for the input
becomes
input {
padding: 30px 10px 10px;
display: block;
width: 100%;
border: 1px solid black;
&::placeholder {
color: transparent;
}
&:focus {
outline: none;
}
&:focus ~ label,
&:not(:placeholder-shown) ~ label{
top: 10px;
color: black;
}
}
also, the attribute in the label is for
(not htmlfor
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.