Search code examples
htmlcss

Placing an icon inside an input HTML


I'm trying to place an icon inside an input in html. I have the code below but I can't get the image to show. I know the path to the image is correct so I can't find what is wrong here. My objective is so that the icon appears on the left side of the input, "glued" to the left border.cand the placeholder appears after the icon.

<input type="text" class="login" id="username" placeholder="Username" required>
.login {
    border-radius: 10px;
    border: none;
    width: 30%;
    display: block;
    text-indent: 3rem;
}

#username {
    background-image: url(../wwwroot/images/login-user.png);
    background-repeat: no-repeat;
    background-position: 2px 3px;
}

Solution

  • If you assume that you know that your image path is correct, try once just an image-tag to see if it displays. Use an Image-Tag to cros-check this.

    <img src="your path" alt="user" />
    

    To solve your problem you can try something like this:

    const label = document.querySelector('label[for="login"]');
    const input = document.querySelector('#login');
    
      // Hide the label when the input is clicked
      input.addEventListener('focus', function() {
        label.style.display = 'none';
      });
    
      // Show the label when the input loses focus
      input.addEventListener('blur', function() {
        // Check if the input is empty before showing the label
        if (input.value.trim() === '') {
          label.style.display = 'inline-block';
        }
      });
    .login {
      position: realtive;
      border-radius: 10px;
      border: none;
      width: 30%;
      display: block;
      padding: 5px;
    }
    
    .fake-placeholder{
      position: absolute;
      top: 10px;
      left: 15px; /* move placeholder to the right when giving pixel sizes */
      color: grey;
    }
    
    .user-image {
      /* define image size here */
      height: 10px;
      width: 10px;
    }
    <label for="login" class="fake-placeholder">
      <img src="path-to-your-image" class="user-image" alt="user-image"/> Username
    </label>
    <input type="text" class="login" id="login" required>

    ``'