invalid input in CSS state/selector

https://codepen.io/JunSu-Ho/pen/KKxLROg so the effect works when input is valid or empty, but not when the user put invalid input, is this can be solved without JS? 🤔 the label should be on top if the input is invalid as well, but not when it's empty it's more clear to see in the codepen link just put some invalid email like abc, the label doesn't react
10 Replies
Joao
Joao•15mo ago
The problem is the :invalid state which starts off as invalid since an empty string is not a valid email address. You can however use :placeholder-shown pseudo element to check if the input's placeholder is being displayed, which only happens when it's empty. Note that you do have to add the placeholder attribute on the input, but it can be left blank if you need to. So then it would look something like this:
.inputBox input:not(:placeholder-shown):invalid ~ label
.inputBox input:not(:placeholder-shown):invalid ~ label
Joao
Joao•15mo ago
Checking if an input is empty with CSS | Zell Liew
Is it possible to know if an input is empty with only CSS? I had that question when I tried to make an autocomplete component for Learn JavaScript. Basically, I wanted to: 1. Hide a dropdown if the input is empty 2. Show the dropdown if the input is filled
JunSu-Ho
JunSu-Ho•15mo ago
that doesn't work at all, with .inputBox input:not(:placeholder-shown):invalid ~ label the label is already up from the start as in case with :invalid which is not the goal
Joao
Joao•15mo ago
Could you describe the goal more clearly, then? I understood that label in red means invalid.
JunSu-Ho
JunSu-Ho•15mo ago
the goal is that when the input is empty the label should be in a place of placeholder (inside of an input, but technically I guess the label stacks on top of an input), and whenever input is not empty whether it's valid or invalid, label should go on top the input (outside of an input space) so that there is no overlapping with input's content text ( the input from the user) so in my case the label does the job of placeholder when an input is empty
Joao
Joao•15mo ago
I don't see the label ever being inside or "on top" of the input, just below or above
JunSu-Ho
JunSu-Ho•15mo ago
empty input
JunSu-Ho
JunSu-Ho•15mo ago
valid input
JunSu-Ho
JunSu-Ho•15mo ago
invalid input, the effect should be the same as valid but it's not, that's the whole problem 🤷
JunSu-Ho
JunSu-Ho•15mo ago