harry-potter
harry-potter

Reputation: 2049

Put a font-awesome icon inside an input tag

I'm trying to put a Font-awesome icon inside an input tag.

This is my HTML code:

<div class="input-group">
        <input class="form-control" type="password" placeholder="Password">
        <span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
</div>

But that icon is bigger than input box as you can see in this picture:

enter image description here

How can I fix the icon?

Upvotes: 8

Views: 40590

Answers (3)

user10523399
user10523399

Reputation: 35

With CSS only

<div class="wrapper">
   <input type="text" class="input">
   <i class="icon" class="fas fa-some-icon"></i>
</div>

Wrap the input and the icon in a 2 columns grid with this column template: 1fr 0

.wrapper {
    display: grid;
    grid-template-columns: 1fr 0;
}

Give the icon a relative position from the right:

.icon{
    width: 40px;
    position: relative;
    right: 45px;
    font-size: 35px;
    line-height: 40px;
    cursor: pointer
    z-index: 1;
}

Give the input a nice padding on the margin:

.input{
    padding-right: 57px;
}

The input will take 100% of the space in the grid and the icon will float atop.

Works well with responsive designs and you can click on the icon.

Upvotes: 1

Finrod
Finrod

Reputation: 2550

Bootstrap 3

Checkout the Bootstrap examples in the Font Awesome documentation:

<div class="input-group margin-bottom-sm">
  <span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
  <input class="form-control" type="text" placeholder="Email address">
</div>
<div class="input-group">
  <span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
  <input class="form-control" type="password" placeholder="Password">
</div>

It should work out of the box, so if you still have height differences, check that there is not other CSS stuff that override your input-group-addon height

Working JSFiddle: https://jsfiddle.net/vs0wpy80

Bootstrap 4

Bootstrap 4 introduced some new classes for input groups, we need to use input-group-prepend and input-group-append:

<div class="input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text"><i class="fa fa-envelope-o fa-fw"></i></span>
  </div>
  <input class="form-control" type="text" placeholder="Email address">
</div>

<div class="input-group mb-3">
  <input class="form-control" type="text" placeholder="Email address">
  <div class="input-group-append">
    <span class="input-group-text"><i class="fa fa-envelope-o fa-fw"></i></span>
  </div>
</div>

Working JSFiddle: https://jsfiddle.net/8do9v4dp/5/

Upvotes: 20

Alan Mroczek
Alan Mroczek

Reputation: 1199

input.form-control{
    margin-top: 0;
}

In my case it helps

Upvotes: 3

Related Questions