Thursday, July 12, 2012

Styling input type file

Styling input type file is not very easy and most of the developers have stopped putting on efforts saying it can't be done!

Well, with CSS opacity and z-index we can style the file input which will work in IE7 and IE8 too. Here is how -

Fiddle Demo: http://jsfiddle.net/dipaks2011/2JJsH/14/

HTML
<div class="styleFileInput">       
  <input type="text" class="browseText" /> //will work as file text field
  <input type="button" value="Browse" class="browseButton" /> // will work as browse button
  <input type="file" size="1" class="theFileInput" /> // Actual input type file which has opacity: 0
</div>

CSS
.styleFileInput{
    position: relative;
}
.browseButton{
    border: 1px solid #b1902c;
    font-size: 0.9em;
    color: #fff;
    padding: 3px 8px;
    border-radius: 4px;
    background: #a7851c;
}
.browseText{
    width: 150px;
    margin: 0 48px 0 0;
    padding: 2px 0;
}
input.theFileInput{
    position:absolute;
    top:0px;
    left: 156px;   
    opacity:0;
    -moz-opacity:0;
    filter:alpha(opacity:0);
    z-index:2;
    width:80px;
    font-size: 1em;
}

jQuery 
$('input[type="text"]').keypress(function(e){
    e.preventDefault();    
});
 
$('.theFileInput').change(function(){
    $('.browseText').val($(this).val());
});

// if condition for Webkit and IE
if($.browser.webkit || $.browser.msie){
    $('.theFileInput').css('left', '190px');
}


Fiddle Demo: http://jsfiddle.net/dipaks2011/2JJsH/14/