How to Customize File Inputs

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.

Create HTML

  • Use a <label> tag with a class name "label".
  • Add an input type "file".
  • Add a <span> element.
<label class="label">
  <input type="file" required/>
  <span>Select a file</span>
</label>

Add CSS

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.

Example of customizing a file input:

<!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>

Result

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".

Example of styling a file input:

<!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>
Do you find this helpful?

Related articles