0

CSS Style an overlaid DIV that looks like placeholder for INPUT

If you go to instagram login page on PC you can see that if you click inside one of the text inputs the placeholder will remain large. When you type characters into the input, the placeholder text shrinks and moves to the top of the input box. it remains there as long as text is in the input box, even if the input loses focus. I am trying to replicate this. is there a way to achieve this using CSS without using JS? I have tried using a DIV after the INPUT element(s), transforming it's position using translateY() or using relative positioning to get the div content where it looks like the placeholder text. Then I can make it transition to smaller text at the top of the input box when the input gets focus, but when the input loses focus, the div (fake placeholder text) content goes back to full size placeholder and overlaps the user input. I have tried the following CSS selector: input:focus ~ .fake-placeholder { ... } <- this works to make the placeholder text transition when input gets focus then to try to maintain the transitioned placeholder, I also tried: input:not(:focus):valid ~ .fake-placeholder { ... } <- this is not giving me "an input that is not focused, but has valid user input [apply to the sibling .fake-placeholder]" as I am wanting. afaik using the placeholder attrib on an input element will always disappear once user inputs some value into the input element. is this right?

25th Apr 2021, 10:59 AM
Nathan Stanley
Nathan Stanley - avatar
1 Odpowiedź
0
I worked this out. The input element in the HTML must be given the 'required' attribute for the :valid pseudoclass to be applied via CSS. Additionally, if you have multiple fake-placeholder elements that are siblings to the input elements the ~ character will apply to all of those sibling elements. To only select the NEXT sibling, use the + character in the selector instead of the ~.
25th Apr 2021, 1:13 PM
Nathan Stanley
Nathan Stanley - avatar