Monday 10 October 2011

How to style an html file input to show only a button

A few days ago, I was trying to take an html input element, and replace it with a simple button that would prompt the user for a file when clicked on. One of the requirements was that the style had to work across FireFox, Internet Explorer (7+) and Safari.

At first, I tried hiding the file input, then displaying a button that would redirect clicks to the file input. This worked on a few browsers, but others would block this technique due to security concerns.

After a quick Google search, I found the following solutions, but they all failed for their own reasons:
  • http://shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom : This involved making the html input invisible, and overlaying it on a button-like div with a background. This worked for the most part, but javascript was used to re-position the file input on the page so the user would always click on the input. Unfortunately, in IE9, the input would follow the mouse outside the div, so if you clicked somewhere completely different, the file input would receive the click and prompt for a file - not good.


I liked Shaun Inman's idea of overlaying a transparent file input on a div with a button-esque background, but the solution for ensuring the file input was clicked didn't satisfy my cross-browser compatibility requirements.


Instead of moving the file input around the page to ensure it got clicked at any location in the div, I decided to try making the file input take up the whole div. This was done by giving the button-div a fixed size, and adding the style "overflow:hidden". This way, the file input can be as big as we need, while not spilling out into the rest of the page.


Here's an example:

HTML
<div class="inputWrapper">
    <input class="fileInput" type="file" name="file1"/>
</div>
CSS
.inputWrapper {
    height: 32px;
    width: 64px;
    overflow: hidden;
    position: relative;
    cursor: pointer;
    /*Using a background color, but you can use a background image to represent a button*/
    background-color: #DDF;
}
.fileInput {
    cursor: pointer;
    height: 100%;
    position:absolute;
    top: 0;
    right: 0;
    z-index: 99;
    /*This makes the button huge. If you want a bigger button, increase the font size*/
    font-size:50px;
    /*Opacity settings for all browsers*/
    opacity: 0;
    -moz-opacity: 0;
    filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)
}
Demo:


Upload!


All you need to do to make the button look nice is apply a background image to the div, and add a 'pressed' background image to the :hover or :active state to give it the impression of being clicked!

No comments:

Post a Comment