Search code examples
htmlcsswidthselectorunderline

how to select the clicked input in css


#registeration_form input:nth-of-type(1):focus ~ #underline1,#registeration_form input:nth-of-type(2):focus  ~ #underline2,#registeration_form input:nth-of-type(3):focus  ~ #underline3,#registeration_form input:nth-of-type(4):focus  ~ #underline4,#registeration_form input:nth-of-type(5):focus  ~ #underline5,#registeration_form input:nth-of-type(6):focus  ~ #underline6{
    transition: 1000ms;
    width: 100%;
}

is there any simple way to write this code ?


Solution

  • I'm not really sure what you're building, but here's a guess (based on naming) that would really simplify your CSS. Basically, I change things to depend on shared classes, not specific ids.

    .field .underline {
      width: 0;
      overflow: hidden;
      transition: 100ms;
      position: absolute;
      bottom: 0;
      left: 0;
      height: 1px;
      background-color: black;
    }
    
    #registeration_form input:focus + .underline {
     width: 100%; 
    }
    
    .field {
      display: inline-block;
      position: relative;
      margin-bottom: .5rem;
    }
    
    .field input {
      border: 1px solid #eee;
      padding: .5rem 1rem;
    }
    <form id="registeration_form">
      <div class="field">
        <input placeholder="Enter Name" aria-label="enter name" type="text" class="input" id="name" name="name">
        <span role="presentation" class="underline"></span>
      </div>
    
      <div class="field">
        <input placeholder="Enter Username" aria-label="enter username" type="text" class="input" id="username" name="username">
        <span role="presentation" class="underline"></span>
      </div>
    
      <div class="field">
        <input placeholder="Enter Email" aria-label="enter email" type="text" class="input" id="email" name="email">
        <span role="presentation" class="underline"></span>
      </div>
    </form>

    jsFiddle