0

I am trying to apply a styling which moves the label to top when the input is in focus. It was working very well before I tried to add validation. Sample Code:-

 <form onSubmit={handleSubmit(onSubmit)}>
    <div className="form__group">
      <input
        className="form__input"
        type="text"
        id="name"
        name="name"
        placeholder=" "
        ref={register}
      />
      {errors.name && <p className="error">{errors.name.message}</p>}
      <label className="form__label" htmlFor="name">
        Name
      </label>
    </div>
    <input type="submit" />
  </form>
  • Normaly if you focus on Input the transition works in the start. The problem is arising when when any validation is not satisfied on submission and an error is being shown.
  • If on submitting form,validation is not satisfied then error messages are fired as per the validation but in this case the transition is not applied even though the input is in focus.
  • As long as the error is visible the styling is not applied and I can't understand why. So far I have deducted that it is overriding the styling of my label.I can't seem to find a way across it.

The styling that is mentioned is:-

    .form__label {
    position: absolute;
    color: #777777;
    transition: all 0.3s;
    cursor: text;
    top: 16%;
    left: 6.5%;
  }
  
  form__input {
    &:focus {
      border: 2px solid blue;
      & + .form__label {
        top: 3px;
        left: 10px;
        color: blue;
      }
    }
    
    &:not(:placeholder-shown) + .form__label {
      top: 3px;
      left: 10px;
      color: blue;
    
    }
  }

The sandbox of the above problem is here

1 Answers1

0

The Problem is that direct sibling is selected in the above case instead of "+" combinator ,"~" combinator should have been used.

  • "+" combinator selects the direct sibling which in case of no errors is the label. so it works in the start but fails in other cases.
  • "~" combinator selects the general sibling which will work in all cases.

In case of errors the label is not a direct sibling that is causing the problem.