Floating label does not work when deleting attribute

I made a floating label for input as shown below. And it works great. But when I remove the required input field, the floating label doesn't work (although I don't need required ). Please suggest some ways to solve this problem.

 input:focus~.floating-label, input:not(:focus):valid~.floating-label { top: 6px; bottom: 12px; left: 20px; font-size: 11px; opacity: 1; } .floating-label { position: absolute; pointer-events: none; left: 20px; top: 18px; text-transform: uppercase; transition: 0.2s ease all; color: #b2b2b2; } 
 <input type="text" id="floating_name" value="" required/> <span class="floating-label">Enter</span> 
+5
source share
2 answers

The input:focus selector selects the input when it receives focus, and the input:not(:focus):valid focus selector selects the input if valid input not focused.

A. when you use the required attribute and do not enter any value into it:

1) Before focusing and loss of focus: nothing is selected. (the initial state)

2) after the focus input is invalid and selected with input:focus .

B. when you remove the required attribute:

1) before choosing a focus using input:not(:focus):valid .

2) after choosing focus using input:focus .

So, the input is selected forever, and the .floating-label will not return to its original state.

in your question you say: "I do not need the required feed"

So, remove input:not(:focus):valid~.floating-label .

Full code:

 input:focus ~ .floating-label { top: 6px; bottom: 12px; left: 20px; font-size: 11px; opacity: 1; } .floating-label { position: absolute; pointer-events: none; left: 20px; top: 18px; text-transform: uppercase; transition: 0.2s ease all; color: #b2b2b2; } 
  <input type="text" id="floating_name" value=""> <span class="floating-label">Enter</span> 
+4
source

The :valid selector only works for constrained form elements. When you remove required , part of your CSS no longer applies. I removed input:not(:focus):valid ~ .floating-label and it works again.

 input:focus~.floating-label { top: 6px; bottom: 12px; left: 20px; font-size: 11px; opacity: 1; } .floating-label { position: absolute; pointer-events: none; left: 20px; top: 18px; text-transform: uppercase; transition: 0.2s ease all; color: #b2b2b2; } 
 <input type="text" id="floating_name" value="" /> <span class="floating-label">Enter</span> 
+1
source

Source: https://habr.com/ru/post/1268741/


All Articles