Styling file input button on various browsers

Wai Park Soon
NoteToPS
Published in
1 min readJan 25, 2013

File input field provides an easy way to allow users to upload file(s) from their system. However its design varies by a great margin across the major modern browsers. However, due to security reasons, styling a file input field isn’t as easy as one might think.

First off, let me quote this frequently quoted link, which enlightened me the direction to solving the problem.

CSS2/DOM — Styling an input type=”file”

However, this method does not work for Firefox. Firefox ignores CSS width property completely. Luckily, we can still change the width of file input field by changing its size attribute.

Lets say we have this file input field which we would like to resize it to be 300px width, including the button.

var target = 300; // Our target
fileInput.size = 1; // Set to minimum size
l1 = fileInput.offsetWidth;
// If the minimum size is still larger,
// we need to move it a little left
if (l1 > target) {
// Set CSS left property
fileInput.style.left = (target — l1) + ‘px’;
} else {
fileInput.size++;
var l2 = fileInput.offsetWidth;
var step = l2 — l1;
var buttonSize = l1 — step;
fileInput.size = Math.round((target — buttonSize) / step);
}

This way, the width of the file input field will be pretty close to our target.

The catch is that CSS width property should not be specified for the file input field. That will cause the value of offsetWidth to not return the on screen width.

--

--