Search code examples
htmlcssfocus

Is there a way in CSS to make a label get a different property when an input is focused without using JS?


What I am trying to do is change the label font color and border color when the input field is focused. Is there a way to make that happen without using JavaScript?

.input-label {
    display: flex;
    align-items: center;
    height: 16px;
    font-weight: 700;
    font-size: 11px;
    letter-spacing: .1px;
    color: #989898;
    text-transform: uppercase;
}
.form-control{
    display: inline-block;
    max-width: 100%;
    word-wrap: normal;
    background: transparent;
    border: none;
    border-bottom: 2px solid #cacaca;
    color: #4a4a4a;
    font-size: 1.19em;
    height: 35px;
    letter-spacing: .2px;
    padding: 7px 0;
    width: 100%;
    resize: none;
}
input:focus{
  /* after the input is focused the labele font color and border color change to something else*/
}
<div class="firstname">
<label for="name" class="input-label" id="name-label">First Name</label>
<input type="text" class="form-control" id="name" placeholder="First Name" required>
</div>


Solution

  • You can use the :focus-within pseudo-class:

    matches an element if the element or any of its descendants are focused.

    You might want to check if the browser compatibility fits your requirements at caniuse.com

    And create a selector like this:

        .firstname:focus-within .input-label {
          color: red;
        }
    

    .input-label {
      display: flex;
      align-items: center;
      height: 16px;
      font-weight: 700;
      font-size: 11px;
      letter-spacing: .1px;
      color: #989898;
      text-transform: uppercase;
    }
    
    .form-control {
      display: inline-block;
      max-width: 100%;
      word-wrap: normal;
      background: transparent;
      border: none;
      border-bottom: 2px solid #cacaca;
      color: #4a4a4a;
      font-size: 1.19em;
      height: 35px;
      letter-spacing: .2px;
      padding: 7px 0;
      width: 100%;
      resize: none;
    }
    
    .firstname:focus-within .input-label {
      color: red;
    }
    <div class="firstname">
      <label for="name" class="input-label" id="name-label">First Name</label>
      <input type="text" class="form-control" id="name" placeholder="First Name" required>
    </div>

    Alternatively, you could place your label after the input and reorder them using CSS.