jQuery: styling file inputs

File inputs are a kind of form controls that are almost impossible to stylize using only CSS. The problem is that this type of form controls is considered sensitive by all browsers due to the security implications that their CSS styles always imply. For example, file inputs cannot be hidden with the visibility property nor with the display property. But a couple of years ago this brilliant article enlighted new ways of handling this problem.

First of all, let's start with a basic form for handling file uploads:

<form action="" method="post">
<div class="file">
    <input type="file" name="file" id="file" />
</div>
</form>

See what's our goal? We want to assign a backgroud image to the container of the file input and then hide the file input itself. How? Before giving you an answer to this question, let's add some CSS styles:

div.file {
 width: 80px;
 height: 22px;
 background: url(file.gif) no-repeat;
}

div.file input {
 display: block;
 width: 80px;
 height: 22px;
}

Finally, we use the opacity property in a cross-browser way thanks to jQuery:

$(document).ready(function() {
    $('#file').css('opacity', '0');
});

I didn't test this solution in IE 6 and 7, so please let me know if something is wrong with these browsers. You can see this demo here.

Leave a Reply

Note: Only a member of this blog may post a comment.