It is possible to customize the <input type=“file”> using a <label>. This is a great solution as pressing a <label> does not activate the focus event for the bound input.
In this snippet, we’re going to show how you can customize a file input without JavaScript.
<label class="label">
<input type="file" required/>
<span>Select a file</span>
</label>
label.label input[type="file"] {
position: absolute;
top: -1000px;
}
.label {
cursor: pointer;
border: 1px solid #cccccc;
border-radius: 5px;
padding: 5px 15px;
margin: 5px;
background: #dddddd;
display: inline-block;
}
.label:hover {
background: #5cbd95;
}
.label:active {
background: #9fa1a0;
}
.label:invalid+span {
color: #000000;
}
.label:valid+span {
color: #ffffff;
}
Here is the full code.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
label.label input[type="file"] {
position: absolute;
top: -1000px;
}
.label {
cursor: pointer;
border: 1px solid #cccccc;
border-radius: 5px;
padding: 5px 15px;
margin: 5px;
background: #dddddd;
display: inline-block;
}
.label:hover {
background: #5cbd95;
}
.label:active {
background: #9fa1a0;
}
.label:invalid + span {
color: #000000;
}
.label:valid + span {
color: #ffffff;
}
</style>
</head>
<body>
<form action="/form/sumbit" method="get">
<label class="label">
<input type="file" required/>
<span>Select a file</span>
</label>
</form>
</body>
</html>
In this example, first, we hide the input which does not take up space in the document layout but still exists and can be activated with the label.
The CSS possibilities of an input file are limitless, so you can use several CSS properties once you understand how this method works.
Now, let's see one another example, where we use the opacity, position, and z-index properties on the "upload".
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
label {
cursor: pointer;
background-color: lightblue;
color: #ffffff;
padding: 10px 20px;
}
#upload {
opacity: 0;
position: absolute;
z-index: -1;
}
</style>
</head>
<body>
<form action="/form/sumbit" method="get">
<label for="upload">Upload a file</label>
<input type="file" name="photo" id="upload" />
</form>
</body>
</html>