Tuesday, 11 July, 2023 UTC


Summary

While working on the example of inverting colors in a picture with Javascript I've realized that adding CSS styling on upload buttons is not that easy.
Until I discovered the ::file-selector-button pseudo-element.
This pseudo element applies to the HTML inputs of the type file:
input[type="file"]::file-selector-button {
   /* styles here */
} 
As a shorthand you actually don’t even need to specify the file input element in front of the pseudo-element:
/* both syntaxes work the same */
input[type="file"]::file-selector-button { } 
::file-selector-button { }
Below is the code for a simple example of styling an input type file upload button with CSS:
::file-selector-button {
  background: orangered;
  color: white;
  border: 1px solid orangered;
  border-radius: 5px;
  padding: 1rem 3rem;
}
Stying the "no file chosen" block
One related question is how can we style the whole widget block of the upload button.
This can be done by using the initial selector of selector input[type="file"]. It will target the whole widget block, that is the button and the text.
So, adding the below CSS:
input[type=file] {
  border: 1px solid orangered;
  color: orangered;
  padding: 1rem;
  border-radius: 5px;
  font-family: "Comic Sans MS", "Comic Sans", cursive;
  font-size: 120%;
  text-transform: lowercase;
}
Will produce this output:
Extra resources and links
You can check out the codepend for this example.
And if you want if you want to see a more complex demo of what is possible with ::file-selector-button take a look here. Cool stuff 💪 !
Also, you can check out the official documentation here. And, the support is great, being now available in all browsers.
Happy styling!
The post CSS styling for the upload buttons of input type file appeared first on Js Craft.