Search code examples
formsruby-on-rails-4devisesimple-formfont-awesome

Adding font-awesome icon inside a input field when using simple-form


I looked and used the solution for placing the font-awesome icons inside an input field box as outlined here.

StackOverflow answer

HTML

<input name="txtName" id="txtName">
<span class="fa fa-user errspan"></span>

CSS

.errspan {
   float: right;
   margin-right: 6px;
   margin-top: -60px;
   position: relative;
   z-index: 2;
   color: gray;
}

But it doesn't really work with simple-form as when you place the icon using css positioning, the icon would be in the wrong place when simple-form shows error messages below the fields themselves.

So for example, if you position the icon to work in one state where it looks great when the error message is displayed like this.

simple-form errors displayed

It ends up being incorrect in another state, like this. enter image description here


Solution

  • The solution turns out to be pretty simple and straight forward.

    Move the icon html to be ahead of the input html like this.

    HTML

    <span class="fa fa-user errspan"></span>
    <input name="txtName" id="txtName">
    

    Then just adjust the CSS positioning so that it fits with this new convention.

    CSS

    .errspan {    
      float: right
      top: 24px
      right: 6px
      position: relative
      z-index: 2
      color: grey
    }
    

    You should be good to go. The icon will always stay exactly where you placed it no matter what the state the form is in.