Styling file input elements can be a challenging task, especially when working with frameworks like Bootstrap. The default file input element is not very visually appealing and does not match the design of other form elements. However, there are ways to style file input elements using HTML, CSS, and a bit of creativity.
Using the hidden
Attribute
One way to style a file input element is by using the hidden
attribute in combination with a label
element. This approach works in all modern browsers, including IE9+.
<label class="btn btn-default">
Browse <input type="file" hidden>
</label>
This technique relies on the HTML5 hidden
attribute, which hides the file input element from view. The label
element is then styled to look like a button, and when clicked, it triggers the file input element.
If you need support for older browsers that do not support the hidden
attribute, you can use the following CSS to shim this feature:
[hidden] {
display: none !important;
}
Legacy Approach for Old IE
For older versions of Internet Explorer (IE8 and below), you can use a different approach. This involves wrapping the file input element in a span
element and using CSS to style it.
<span class="btn btn-default btn-file">
Browse <input type="file">
</span>
The corresponding CSS for this approach is:
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
This CSS makes the file input element invisible and positions it absolutely within the span
element. The span
element is then styled to look like a button.
Displaying Selected Files
To display the selected files, you can use JavaScript to update the text of a span
element.
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" style="display:none"
onchange="$('#upload-file-info').text(this.files[0].name)">
Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span>
This code uses jQuery to update the text of the #upload-file-info
span element with the name of the selected file.
Alternative Approaches
There are also alternative approaches to styling file input elements, such as using a library like Jasny’s fork of Bootstrap or using a trick like the one described on Quirksmode.org. However, these approaches may require additional dependencies or complex CSS rules.
In conclusion, styling file input elements with Bootstrap can be achieved using a combination of HTML, CSS, and JavaScript. By using the hidden
attribute, legacy approach for old IE, and displaying selected files, you can create visually appealing file input elements that match your design.