This question already has an answer here:
- Styling an input type=“file” button 39 answers
I would like to style <input type="file" />
using CSS3.
Alternatively, I would like user to press on a div
(that I will style) and this will open the Browse window.
Is that possible to do that using HTML, CSS3, and Javascript / jQuery only ?
The fake div is not needed! No Js no extra html. Using only css is possible.
The best way is using the pseudo element :after or :before as an element overt the de input. Then style that pseudo element as you wish. I recomend you to do as a general style for all input files as follows:
--> DEMO
When you retreive the value of an input field, browser will return a fake path (literally C:\fakepath[filename] in Chrome). So I would add the following to the Javascript solutions:
Ofc, it could be done in a single line.
Here is how to do it using HTML, CSS and Javascript (without any frameworks):
The idea is to have the
<input type='file'>
button hidden and use a dummy<div>
that you style as a file upload button. On click of this<div>
, we call the hidden<input type='file'>
.Demo:
Here is a solution with a text field where the user types in the (relative) pathname of the file copy on the server (if authorized) and a submit button to browse the local system for a file and send the form:
The scripting part hides the file input, clicks it if the user clicks on the submit button, submits the form if the user has picked up a file. If the user tries to upload a file without entering a filename, the focus is first moved to the text field for the filename.
Simply style the submit button for a perfect result:
I made a custom style for this as well. Check it out
JS Fiddle Demo - Custom Input type="file"
HTML
CSS
JQuery
Also add to external resources tab:
https://github.com/necolas/css3-github-buttons/blob/master/gh-buttons.css
Here's an example that I'm using that utilizes jQuery, I've tested against Firefox 11, and Chrome 18, as well as IE9. So its pretty compatible with browsers in my book, though i only work with those three.
HTML
Here's a basic "Customizable" HTML structure.
CSS
Here's a sample of my CSS
JavaScript
This is the heavy lifter.
Explanation
The HTML is pretty straight forward, just a simple element, i include the button so it can be named independently from the rest, sure this could be included in the JavaScript, but simply put, I'm a bit on the lazy side. The code searches for all inputs with a class of smallInput that have the type of file this allows you to define default HTML and fallback form structure in case a browser decides to be a pain.
This method only uses JavaScript to ensure delivery, it does not alter any browser behaviors in regards to the file input.
You can modify the HTML and JavaScript to make it very robust, this code suffices my current project so i doubt I'll be making any changes to it.
Caveats