How to style a button to upload a file

This is what I’m doing right now at work: trying to style an input button to upload a file.

So, if you simply type the code like this:

<input type="file">

this is what you get:

upload-no-styleThe problem is: how do you style the button ( written here in Italian, “scegli file” - “choose file”) to match the style of your website?

For example, in my works I use bootstrap like half dozen million of people of the world does. I want the style of this button to match the style of the others. Also, I don’t want to see the “nessun file selezionato” (“no file selected”) written aside (it can’t be styled too!).

The solution

This is something I have discovered on StackOverflow and by now it is my favorite hack.

<div class="form-group">
    <label for="inputFile" class="btn btn-primary">
      <input id="inputFile" type="file" style="display:none;">
        Select File
    </label>
</div>

This is how it is rendered by the majority of browsers:

upload-button-styledThe first “this is a button” is a normal html

How the hack works?

When you wrap a

Another help is coming from the style=”display:none;” attribute. It will hide the input element from the screen, so that we only see the label for the input.

Compatibility

Boring part. It seems that it doesn’t work very well with IE8 and before. Have a look on Stack Overflow on how to make it work. I don’t care, since I don’t use IE and I generally target my work to the latest browsers and platforms.

Related Posts: