2

I want to float the label when users focus on textboxes as in this example, but on focus the label does not move upwards. Below is my code.

.input-base-input {
    width: 100%;
    font-size: 15px;
    padding-top: 8px;
    border: none;
    border-bottom: .5px solid #a9abb3;
    background: transparent;
    font-weight: 600;
}

.input-base-input:focus ~ .input-base-label,
.input-base-input:not(:focus):valid ~ .input-base-label{
    display: block;
    position: absolute;
    top: 10px;
    transition-property: top;
    transition-duration: .1s;
}

.input-base-label {
    position: absolute;
    pointer-events: none;
    top:-10;
    transition-property: top;
    transition-duration: .1s;
}
<label for="pincode" class="input-base-label">Pin Code</label>
<input class="input-base-input" maxlength="6">
isherwood
  • 58,414
  • 16
  • 114
  • 157
user3653474
  • 3,393
  • 6
  • 49
  • 135

1 Answers1

1

First, this CSS:

.input-base-input:focus ~ .input-base-label

will select the label which comes after the input (and not before as shown in your code), so first change the order of input and label.

Second, you have not specified the correct value for the top property of .input-base-label:

.input-base-label {
  ...
  /* Not correct */
  top: -10;
  /* Correct */
  top: -10px;
  /* or */
  top: 0;
  ...
}

Third, :valid selector will make your input valid even if it's empty (so your label will be floated on the page load). To resolve this with CSS-only approach, add required attribute to the input.

So, your final result might look like this:

<input class="input-base-input" id="pincode" name="pincode" maxlength="6" required>
<label class="input-base-label" for="pincode">Pin code</label>

.input-base-input {
    width: 100%;
    font-size: 15px;
    padding-top: 8px;
    border: none;
    border-bottom: .5px solid #a9abb3;
    background: transparent;
    font-weight: 600;
}

.input-base-label {
    position: absolute;
    pointer-events: none;
    top: 0;
    transition-property: top;
    transition-duration: .1s;
}

.input-base-input:focus ~ .input-base-label,
.input-base-input:not(:focus):valid ~ .input-base-label {
    display: block;
    top: -10px;

    /* The following properties are not needed as they are specified previously */
    /*
    position: absolute;
    transition-property: top;
    transition-duration: .1s;
    */
}
<input class="input-base-input" id="pincode" name="pincode" maxlength="6" required>
<label class="input-base-label" for="pincode">Pin code</label>
Rustem Gareev
  • 804
  • 1
  • 7
  • 14