If you have ever tried it, you will know that it can be troublesome to implement a unified upload file button using pure CSS styles and HTML. Take a look at the screenshots from different browsers below. It's obvious that they look very different.
Our goal is to create a simple upload file button implemented in pure CSS that has the same look and layout in all browsers. We can do it like this:
Step 1. Create a simple HTML tag
<div class="fileUpload btn btn-primary"> <span>Upload</span> <input type="file" class="upload" /> </div>
Step 2: CSS: It’s a little tricky
.fileUpload { position: relative; overflow: hidden; margin: 10px; } .fileUpload input.upload { position: absolute; top: 0; right: 0; margin: 0; padding: 0; font-size: 20px; cursor: pointer; opacity: 0; filter: alpha(opacity=0); }
For simplicity, I used a button with Bootstrap CSS styles applied (div.file- upload).
Demo:
Upload button to display the selected file
Unfortunately, pure CSS cannot do this. However, if you really want to display the selected file, the following JavaScript snippet can help you.
JavaScript:
document.getElementById("uploadBtn").onchange = function () { document.getElementById("uploadFile").value = this.value; };
DOM:
<input id="uploadFile" placeholder="Choose File" disabled="disabled" /> <div class="fileUpload btn btn-primary"> <span>Upload</span> <input id="uploadBtn" type="file" class="upload" /> </div>