Search code examples
htmlcssfocuscss-transitions

input focus placeholder top not working on input readonly and placeholder


I have created a input box like these:

enter image description here

but when I use input box readonly it is not working. Here is my working snippet:

.myinput input:focus {
  outline: none;
}

.myinput {
  position: relative;
  width: 100%;
}

.myinput .inputText {
  width: 100%;
  outline: none;
  border: none;
  border-bottom: 1px solid #ccc;
  box-shadow: none !important;
  border-radius: unset !important;
}

.myinput .inputText:focus {
  border-color: #3399FF;
  border-width: medium medium 2px;
}

.myinput .floating-label {
  position: absolute;
  pointer-events: none;
  top: 25px;
  left: 0;
  transition: 0.2s ease all;
  color: #aaa;
}

.myinput input:focus~.floating-label,
.myinput input:not(:focus):valid~.floating-label,
.myinput input:not(:placeholder-shown):not(:focus):valid + .floating-label,{
  top: 0px;
  left: 0;
  font-size: 13px;
  opacity: 1;
  color: #3399FF;
}
<div class="myinput">
  <br>
  <input type="text" name="coupon" class="inputText" value="Test" placeholder="" readonly>
  <span class="floating-label">Enter Coupon Code</span>
</div>

When i removed required option from AddressLine2 input field it focused on top. See image below:

enter image description here

Want to fix the readonly and placeholder isseus!


Solution

  • Use the :read-only pseudo-selector to make the placeholder move to the top.

    .myinput input:read-only + .floating-label

    Note: you can replace the general sibling ~ combinator with the adjacent sibling + combinator, since the .floating-label comes right after the input.

    Example:

    .myinput input:focus {
      outline: none;
    }
    
    .myinput {
      position: relative;
      width: 100%;
    }
    
    .myinput .inputText {
      width: 100%;
      outline: none;
      border: none;
      border-bottom: 1px solid #ccc;
      box-shadow: none !important;
      border-radius: unset !important;
    }
    
    .myinput .inputText:focus {
      border-color: #3399FF;
      border-width: medium medium 2px;
    }
    
    .myinput .floating-label {
      position: absolute;
      pointer-events: none;
      top: 25px;
      left: 0;
      transition: 0.2s ease all;
      color: #aaa;
    }
    
    .myinput input:focus + .floating-label,
    .myinput input:not(:placeholder-shown):not(:focus):valid + .floating-label,
    .myinput input:read-only + .floating-label {
      top: 0px;
      left: 0;
      font-size: 13px;
      opacity: 1;
      color: #3399FF;
    }
    <div class="myinput">
      <br>
      <input type="text" name="coupon" class="inputText" value="Read Only" placeholder="" readonly>
      <span class="floating-label">Enter Coupon Code</span>
    </div>
    
    <div class="myinput">
      <br>
      <input type="text" name="coupon" class="inputText" placeholder="&nbsp;">
      <span class="floating-label">Enter Coupon Code</span>
    </div>