DEV Community

Cover image for How to style an input file with some help from Bootstrap and FontAwesome
Michele Mirandola
Michele Mirandola

Posted on

How to style an input file with some help from Bootstrap and FontAwesome

You know, styling an is hard, basically due to some standard behaviors of the browsers that keeps this kind of input aspect a bit ugly.

So, i'll show you a simple method to use when you have to enchance a form with this kind of input, assuming you're using Bootstrap in your project.

PS: You can check the final markup here con this Pen

Here is the main markup (as you can see this is a "basic" bootstrap form-group, except for the "file-field" class that we will use it to customize our field):

<div class="form-group file-field">
    <input class="form-control" type="file" name="attachment" id="contact-attachment">
    <label class="form-label" for="contact-attachment">Select the  file...</label>
</div>
Enter fullscreen mode Exit fullscreen mode

The key for our porpuse will be style the <label> to "cover" the <input>. Let's see how to do this:

.file-field label {
    cursor: pointer;
    /* Here we will "duplicate" a bootstrap basic style */
    height: 36px;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    padding: .375rem .75rem;
    width: 100%;
    /* Style as you please, it will become the visible UI component. */
}
.file-field input[type="file"] {
    opacity: 0;
    position: absolute;
    z-index: -1;
}
Enter fullscreen mode Exit fullscreen mode

Here it is! We've just created a basic workaround to "cover" the ugly part of the borowser aspect of the input.

But we can do slightly better adding an icon with my favourite service FontAwesome.

We can add a <i class="faS fa-folder mr-2"></i> inside our <label>:

<div class="form-group file-field">
    <input class="form-control" type="file" name="attachment" id="contact-attachment">
    <label class="form-label" for="contact-attachment"><i class="fas fa-folder mr-2"></i>Select the  file...</label>
</div>
Enter fullscreen mode Exit fullscreen mode

We can also style the icon on the label "hover":

.file-field label:hover i {
    color: purple; /* or whatever color you want */
}
Enter fullscreen mode Exit fullscreen mode

Pretty easy, isn't it?. Let me know if you have any trouble, I left a bug on the code etc... ( and forgive me for my english of course :-) )

Have a nice day!

Photo by James Harrison on Unsplash

Top comments (0)