Replace input type=file by an image

Nicolas picture Nicolas · May 18, 2010 · Viewed 231k times · Source

Like a lot of people, I'd like to customize the ugly input type=file, and I know that it can't be done without some hacks and/or javascript. But, the thing is that in my case the upload file buttons are just for uploading images (jpeg|jpg|png|gif), so I was wondering if I could use a "clickable" image which would act exactly as an input type file (show the dialog box, and same $_FILE on submitted page).
I found some workaround here, and this interesting one too (but does not work on Chrome =/).

What do you guys do when you want to add some style to your file buttons? If you have any point of view about it, just hit the answer button ;)

Answer

hardsetting picture hardsetting · Sep 14, 2013

This works really well for me:

.image-upload>input {
  display: none;
}
<div class="image-upload">
  <label for="file-input">
    <img src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg"/>
  </label>

  <input id="file-input" type="file" />
</div>

Basically the for attribute of the label makes it so that clicking the label is the same as clicking the specified input.

Also, the display property set to none makes it so that the file input isn't rendered at all, hiding it nice and clean.

Tested in Chrome but according to the web should work on all major browsers. :)

EDIT: Added JSFiddle here: https://jsfiddle.net/c5s42vdz/