How To Customize The Input File Button

CSS

05/04/2021


Customizing the input file button used to be notoriously difficult. As such, developers had to come up with a creative workaround. Fortunately, things have changed for the better as CSS specifications evolved. Nonetheless, I'd like to cover both the workaround and the new way of customizing the button.

So let's start with the former! 😜

The old way

The idea behind the workaround is relatively simple. As you may or may not know, clicking on the label of an input of type file can trigger the file dialog as well. This allows us to simply place our custom button inside the label and then hide the original input button.

Layout does not matter

Regardless of whether you decide to wrap the label around the input or keep both elements separate, the solution works. And to hide the input element, simply add on the hidden attribute.

HTML
<input type="file" id="upload-file" hidden />
<label for="upload-file">Upload</label>
<!-- OR -->
<label>
<input type="file" hidden />
Upload
</label>

Styling the button

Depending on your circumstances, you may prefer to either:

  • Style the label so it looks like a button, or
  • Add an element (e.g. div) inside the label that acts and looks like a button

Adding a button element inside the input label will unfortunately not trigger the file dialog. Wacky, I know... 😅

You can play around with some code I've prepared on Codepen. It covers what I've just mentioned above.

The new way

Unknown to many, there's actually a CSS pseudo-element called ::file-selector-button, or ::-webkit-file-upload-button for WebKit/Blink compatible browsers, which allows you to effortlessly style the input button. It has finally garnered enough support by most browsers that it can actually be used.

CSS
input[type=file]::file-selector-button {
/* Add properties here */
}

WRITTEN BY

Code and stuff