D.Hodges
D.Hodges

Reputation: 2079

Is there a way to replace the default choose file icon with a custom image background for an input field?

Since I have a PWA i can only find tutorials for uploading images using the input field. That part is working but I'm trying to replace the default 'choose file' icon with a custom image.

Here is a pic of what I have: enter image description here

I don't want the 'choose file' image to show up at all. Also there's a default wording 'No file chosen'. I just want the image that's in the background but I haven't found anything online to shows how to replace it.

  .input_pic {
    background-image: url("../../../assets/image/SpaghettiPlus2.png") !important;
    background-repeat: no-repeat;
}
            <div *ngSwitchCase="'false'">
                <ion-input class="input_pic" type="file"
                id="capture"
                accept="image"
                capture (change)="uploadFromFile($event, 'photo1')"></ion-input>              
            </div>

Upvotes: 2

Views: 743

Answers (2)

Kaiido
Kaiido

Reputation: 136746

Simply redirect the click on your image to the input, and hide the input completely:

document.querySelector("img").onclick = (evt) => {
  document.querySelector("input").click();
};
input { display: none; }
img { cursor: pointer; }
<img src="https://picsum.photos/100/100">
<input type="file">

Upvotes: 0

lastr2d2
lastr2d2

Reputation: 3968

It's possible to style the choose button with ::file-selector-button, however, you can't do anything about the no file chosen text with this solution.

Well, you can, by setting color to transparent, but it's not perfect.

#browse::file-selector-button {
  display: none;
}

#browse {
  color: transparent;
}

#browse::before {
  content: url('https://via.placeholder.com/150');
}
<input type="file" id="browse">

Another solution is to hide the entire input control and use a label to trigger the browse event of the input control.

label {
  display: block;
  width: 150px;
  height: 150px;
  background: url("https://via.placeholder.com/150");
  cursor: pointer;
}

#browse {
  display: none;
}
<label for="browse" title="click to browse file"></label>
<input id="browse" type="file"> </input>

Upvotes: 1

Related Questions