Home  >  Article  >  Web Front-end  >  How to change the default upload file button style using pure html and css

How to change the default upload file button style using pure html and css

伊谢尔伦
伊谢尔伦Original
2016-11-22 15:22:531506browse

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:

How to change the default upload file button style using pure html and css

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>

How to change the default upload file button style using pure html and css


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn