Styling HTML file input button with Pure CSS (without losing the file name text)
I was creating a career page on a website for a client, My requirement was simple. I just needed to style the file input button of HTML in a way that it matches with my other Bootstrap buttons. I learnt that there is no traditional way to override the default button styles for the file input.
I went through a number of solutions on the internet, The solutions with pure CSS totally removed the file name text beside the button and the ones which display used a lot of javascript to do it.
I Personally prefer to use minimal Javascript to style basic elements, hence I came up with this solution which uses only CSS and still retains the text which we all want.
Let’s start with the basic HTML mockup
It consists of the following:
- A file input tag
- A label tag with
for
linked to the input tagid
- A wrapper container
<div>
to how these two elements
<div class=”button-wrap”>
<label class =”new-button” for=”upload”> Upload CV
<input id=”upload” type=”file” >
<div>
Now Let’s style the <label>
tag to give it a button like look and then place it over the existing file input button.
.new-button {
display: inline-block;
padding: 8px 12px;
cursor: pointer;
border-radius: 4px;
background-color: #9c27b0;
font-size: 16px;
color: #fff;
}input[type="file"] {
position: absolute;
z-index: -1;
top: 6px;
left: 0;
font-size: 15px;
color: rgb(153,153,153);
}.button-wrap {
position: relative;
}
That’s it! You will get simple bootstrap like button for file input. Live CodePen link below.