Hello. There is an input to which a label is attached through for. How to contact him in the css? Through input:focus + label does not work.

Codepen: https://codepen.io/Alexxosipov/pen/rYLvYB

Code:

 <div class="input_div"> <input type="text" id="promocode_input" name="promocode"><br> <label for="promocode_input">Введите промокод</label> </div> <style> @bluebtn: rgb(48,40,152); body { font-family: arial; } input { max-width: 220px; border: none; border-bottom: 1px solid lighten(@bluebtn, 30%); padding: 10px; display: block; float: left; margin: 15px auto 0; border-radius: 0; padding-left: 3px; width: 95%; outline: none; } .oute { margin: 30px auto; } .input_div { position: relative; display: block; label { position: absolute; top: 24px; transition: 0.25s; display: block; left: 3px; } input:focus + label { top: 10px; } } </style> 
  • and what's stopping you from addressing him directly? what is the point? - Air

2 answers 2

CSS selectors

Option number 1

 input:focus ~ label[for="promocode_input"] { top: 10px; } 

Option number 2

  input:focus ~ .input_div label { top: 10px; } 

Option number 3

  input:focus ~ label { top: 10px; } 

div p - p elements that are descendants of div.

div> p - only immediate descendants

div ~ p - right neighbors: all p at the same level of nesting, which go after the div.

div + p is the first right neighbor: p at the same nesting level that comes right after the div (if any).

  • Thank you very much for the detailed explanation :) - Alexxosipov

+ points to the element following the previous one. In your case, the trace. element is <br> . Use the following construction instead: input:focus ~ label

https://codepen.io/anon/pen/ZaOoMz