Put a font-awesome icon inside an input tag

a 夏天 提交于 2019-12-30 05:03:37

问题


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:

How can I fix the icon?


回答1:


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/




回答2:


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

In my case it helps




回答3:


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.



来源:https://stackoverflow.com/questions/39959066/put-a-font-awesome-icon-inside-an-input-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!