Working on Blade CSS and found myself wanting to add icons to input fields, including those where the type was declared.
There are a few that don't need icons ... date, file, and number. Those have a pre-built appearance or an icon defined by the browser (date, for example, has a calendar icon at the far right of the input field).
I looked through some of the major CSS Frameworks for inspiration. Of course, there's no inspiration there to be had. Bulma, for example, has specific CSS classes to position icons. Want the icon aligned at the right of the input? Use a custom class. Want to make the icon aligned left? Use a custom class for that too. There's two custom classes in Bulma actually ... one for the input and one for the icon. Well, three if you consider the wrapper too. I've really never found any of Bulma CSS code to be inspiring ...
I ended up writing some CSS and kept it as semantic as possible. And, wow ... it's impressed even me. Only one class needed, and that's for the wrapper. And, a total of 23 lines of code. And that includes positioning the icon on the left or the right. I likely have one aspect to modify to apply to all the different input sizes, but that is trivial.
Here's the CSS:
.icon-group {
position: relative;
i.fa {
background-color: #eee;
color: #aaa;
height:calc(100% - 2px);
padding-top:0.5rem;
position: absolute;
bottom:1px !important;
left:1px;
right:auto;
top: 1px;
text-align:center;
width:36px;
}
input+i.fa {
left:auto;
right: 1px;
}
i.fa+input {
padding-left:40px;
}
}
And here it is in action in the HTML:
<p>
<div class="icon-group">
<i class="fa fa-user fa-lg" aria-hidden="true"></i>
<input type="text" placeholder="Your name">
</div>
</p>
<p>
<div class="icon-group">
<input type="text" placeholder="Your name">
<i class="fa fa-user fa-lg" aria-hidden="true"></i>
</div>
</p>
That generates:
![]()
That's a screen shot, so it may appear as a different size that an actual HTML page. Still an amazing feat for just a few lines of CSS. Note the calculations for positioning to get the input border to show through. z-index would not work in this case, that's why there's some fancy footwork going on with the calculations.
You can also use labels with the icon positioning CSS ... just put the label above the wrapper HTML code.
How does the positioning work for left or right? Its really simple. For left positioning, put the <i> tag before the <input> tag. For right positioning, put the <i> tag AFTER the <input> tag. The CSS is what makes that all work and keeps the HTML code clean without a bunch of useless CSS classes.
Enjoy!