My input field has a label in the same position as the placeholder. When I click on the input field, the label moves up and appears at the top border of the input field, which looks really nice.
However, I'm encountering an issue with the ":valid" pseudo-class. I've written CSS code to lift the label up when the input field is in focus and contains valid input (for example, for an email field, if the content is an email address).
.wrapper {
background-color: rgba(31, 41, 55, 1);
height: 100vh;
width: 100vw;
display: flex;
flex-direction: row;
justify-content: center:
align-items: center;
}
.inputBox {
position: relative;
margin: 100px;
}
.inputField {
width: 100%;
padding: 0.5rem;
border-radius: 0.5rem;
background-color: rgba(31, 41, 55, 1);
border: 1px solid rgba(233, 186, 32, 0.25);
outline: none;
font-size: 1em;
color: rgba(255, 255, 255, 0.25);
}
.inputField:-webkit-autofill,
.inputField:-webkit-autofill:hover,
.inputField:-webkit-autofill:focus {
border: 1px solid rgba(233, 186, 32, 0.25);
-webkit-box-shadow: 0 0 0px 1000px rgba(31, 41, 55, 1) inset;
-webkit-text-fill-color: rgba(255, 255, 255, 0.25);
}
.label {
position: absolute;
left: 0;
top:0;
padding: 0.5rem;
pointer-events: none;
font-size: 1em;
color: rgba(255, 255, 255, 0.25);
text-transform: uppercase;
transition: all 0.5s ease-in-out;
}
.inputField:valid + .label,
.inputField:focus + .label {
color: #44f8da;
transform: translateX(10px) translateY(-5px);
font-size: 0.65em;
padding: 0 0.5rem;
background-color: rgba(31, 41, 55, 1);
border-left: 1px solid #44f8da;
border-right: 1px solid #44f8da;
letter-spacing: 0.2em;
}
.inputField:valid,
.inputField:focus {
border: 1px solid #44f8da;
}
<div class="wrapper">
<div class="inputBox">
<input
type="email"
name="email"
class="inputField"
required
/>
<span class="label">Email</span>
</div>
</div>
Now, if I add some text (not an email) in the input field and unfocus the input field, presumably the label will return to its placeholder position. However, what I want is to keep the label at the top when any value is present, but with a red border to indicate it's invalid. My current code works for valid input.
If I try using .inputField:not(:placeholder-shown) and apply the styles to the label, it remains at the top and doesn't return to the placeholder position regardless of whether there is any value or not. Additionally, it doesn't check for validity.
What is the best possible way to achieve this?