Input with icon inside using HTML and CSS

In this tutorial we’ll learn how to create an input field with icon inside using HTML and CSS.

First create an empty folder, then open Visual Studio Code and open the folder.

Next, create two index.html and style.css files. Open the index.html file and add the following code to include both style.css and font-awesome:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <!-- First we need to include the style.css and font-awesome -->  
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css'>  
    <link rel="stylesheet" href="./style.css">  

    <title>Input with Icon Example</title>  
</head>

Next, add the following content to index.html inside the body tag:

 <h1>Input with Icon Example</h1>  
    <p>In this tutorial I'll show you how to use an input field with an icon</p>  
    <div class="inputicon">  
        <i class="fa fa-search"></i>  
        <input type="text" placeholder="Search">  
    </div>

We added a header and paragraph just for the sake of explaining to the user what we are doing. This is totally optional.

Next, we added the div that contains our input field and icon.

Next, we need to style the div by targeting the custom inputicon class we added to the div. In the style.css file add the following code:

.inputicon {  
    position: relative;  
}  

.inputicon i {  
    position: absolute;  
    padding: 1px 6px;  
}  

.inputicon input {  
    padding-left: 25px;  
}

We first give the div a relative position and the icon an absolute position, then we fix the padding of the icon and the input field.