Adsense 1

Tuesday, April 15, 2014

Simplest Cross-Browser Custom Upload Button Using Basic CSS

If you google for custom upload button, you will find tons of blogs and stackoverflow answers that employ cool and complicated CSS tricks to customize the input file button. Some even require JavaScript. Those are well and good but I also believe in the KISS principle.

Well, enough of the rumblings and let's dive in to the code.

First, let's see how the default input file button looks like.

Code:
<input type="file" name="upload_file" />

Demo:


That's how the default input file control looks like in this browser. And it looks different on every browser. In Google Chrome, it displays "Choose File" button and next to it is the text "No file chosen". In Firefox, the button is called "Browse..." and the text says "No file selected.". In Internet Explorer, there is a textbox and a "Browse..." button. Styling this control is very limited. For one, you can't change the button label.

Now, let's see a customized version of it.

Code:
<label><input type="file" name="upload_file" style="position:absolute; left:-9999px" />Upload</label>

Demo: (Click Upload to see that the browser's File dialog appears)
 


That's it! That's the simplest cross-browser (did I mention it works in IE6?) custom file upload button ever, as in ever. No advanced CSS3 tricks or browser vendor specific CSS required, nor JavaScript nor jQuery, just plain old <label> tag and the associated input file inside it. Of course, you can move the inline style to external CSS but that's just basically about it.

Now let's make it more fancy and style it like a button.

Code:
<style>
.custom-upload {
    background-color: #008000;
    border: 1px solid #006400;
    border-radius: 4px;
    cursor: pointer;
    color: #fff;
    padding: 4px 10px;
}
.custom-upload input {
    left: -9999px;
    position: absolute;
}
</style>
<label class="custom-upload"><input type="file" name="upload_file" />Upload</label>


Demo: (Click Upload to see that the browser's File dialog appears)
 


You can also attach event handlers to the input file as you normally would.

That's how simple it is. Enjoy! :)

Let me know what you think in the comments.

9 comments:

  1. I like it! Thank you for the post. Here is another example rhetorical to this blog. Check it out!
    http://webmuch.com/how-to-customize-a-file-upload-button-using-css3-html5-and-javascript/

    ReplyDelete
  2. Replies
    1. It works in Firefox. Try this jsfiddle in Firefox.

      http://jsfiddle.net/noypiscripter/4fxvvwfe/

      Delete
  3. I like it . So beautiful. And also thanx .

    ReplyDelete
  4. Nice. Simple but work on all browsers, include IE Mobile.

    ReplyDelete
  5. Fantastic Dude!!, it looks really pleasant!

    ReplyDelete
  6. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.have a peek at this site
    school signs uk

    ReplyDelete