Cover Image for How to put an icon inside an input element in a form using CSS
267 views

How to put an icon inside an input element in a form using CSS

To put an icon inside an input element in a form using CSS, you can use the background-image property or utilize an <i> or <span> tag with an icon font or SVG. Here are two approaches:

  1. Using background-image:

HTML:

<div class="form">
  <input type="text" class="input-with-icon" placeholder="Search">
</div>

CSS:

.form {
  position: relative;
}

.input-with-icon {
  padding-left: 30px; /* Adjust the padding as needed */
  background-image: url('path/to/icon.png');
  background-repeat: no-repeat;
  background-position: 5px center; /* Adjust the positioning of the icon */
  background-size: 20px; /* Adjust the size of the icon */
}

In this approach, you set the background-image property of the input element to the URL of the icon image. Adjust the background-position and background-size properties to position and size the icon appropriately within the input element.

  1. Using an <i> or <span> tag with an icon font or SVG:

HTML:

<div class="form">
  <input type="text" class="input-with-icon" placeholder="Search">
  <i class="icon fas fa-search"></i> <!-- Replace with your desired icon class -->
</div>

CSS:

.form {
  position: relative;
}

.input-with-icon {
  padding-left: 30px; /* Adjust the padding as needed */
}

.icon {
  position: absolute;
  top: 50%;
  left: 10px; /* Adjust the positioning of the icon */
  transform: translateY(-50%);
  font-size: 16px; /* Adjust the font size of the icon */
}

In this approach, you add an <i> (or <span>) tag with a class that corresponds to an icon font or SVG library (e.g., Font Awesome). Position the icon absolutely within the form container using CSS positioning (position: absolute) and adjust the top, left, and font-size properties to position and style the icon according to your preference.

Remember to include the necessary CSS or icon font libraries in your project to ensure the icons are correctly displayed.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS