I'm posting this because (to my surprise) there was no other place I could find that recommended this.
There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label>
tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].
The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:
label.myLabel input[type="file"] {_x000D_
position:absolute;_x000D_
top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
border: 2px solid #AAA;_x000D_
border-radius: 4px;_x000D_
padding: 2px 5px;_x000D_
margin: 2px;_x000D_
background: #DDD;_x000D_
display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
<input type="file" required/>_x000D_
<span>My Label</span>_x000D_
</label>
_x000D_
I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden
or display:none
file-input). I've tested in emulated IE7 and up, and it worked perfectly.
<button>
s inside <label>
tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.for
attribute is defined, its value is used to trigger the input with the same id
as the for
attribute on the <label>
.