Search code examples
htmlcssw3.css

How to Place Search Icon inside Text Input Field using W3.CSS


I am creating a search box for a sidebar. I need to place search icon inside the text feild and can't seem to get the result.

<input class="w3-input" type="text" placeholder="Search..."> <i class="w3-input-icon fa fa-search"></i>

It's giving output like this:

enter image description here

How to align it at the right side.


Solution

  • You can't place an HTML element inside an input, but you can overlay it (place it on top). Below, the search icon is placed over the input field by absolutely positioning it within a relatively positioned container, ensuring it appears on top of the input and to the right side. I've added pointer-events:none; so when the user clicks the icon, it does not block interaction with the input.

    .search-box {
      position: relative;
      display: inline-block;
    }
    
    .w3-input {
      padding-right: 30px;
    }
    
    .search-icon {
      position: absolute;
      right: 0;
      top: 0;
      padding: 12px 12px;
      pointer-events: none;
    }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/w3-css/4.1.0/w3.min.css" integrity="sha512-Z6UIAdEZ7JNzeX5M/c5QZj+oqbldGD+E8xJEoOwAx5e0phH7kdjsWULGeK5l2UjehKtChHDaUY2rQAF/NEiI9w==" crossorigin="anonymous" referrerpolicy="no-referrer"
    />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
    <div class="search-box">
      <input class="w3-input" type="text" placeholder="Search...">
      <i class="fa fa-search search-icon"></i>
    </div>