css: disabled styling

as your forms grow in complexity, you’ll probably find a need to temporarily disable an input – either a button, a text box, or some other element.

this is quite easy in html – the disabled attribute comes to the rescue. but just how do you style those fields, and convey that they are temporarily disabled?

let’s consider this standard input field:


pretty standard stuff. your web browser will automatically style it a little, but mostly just prevent the user from editing without any real visual hints. but let’s add some basic css to convey the state of the input, and to standardise it across our site and on most platforms. if we add the following css:

input[disabled] {
        border: 1px solid #999;
        background-color: #ddd;
}

but wait – our demo uses inline styles, but your browser might not have just styled that properly if we used a full css declaration. we don’t set a value for the disabled attribute – it’s a minimized attribute. to get ie to play nicely with it (and for xhtml), we’ll have to set the value to “disabled”:

if possible, just for total compatibility, we can also add a “disabled” class that ie6 will respect and apply styles for correctly.

we can then change the css selector we’re using:

input[disabled="disabled"], input.disabled

and we’re done! this works across every major browser – ie6+ and ff1.0+ tested, and safari 3 / opera 9.5 should be fine as well. the sitepoint css reference has further information on compatibility, available here.

finally, if you want to see how firefox styles disabled fields by default, load up your resource://gre/res/forms.css file (you’ll have to copy and paste it to your address bar). there are a number of lengthy selectors with just a few rules, but here’s the big one, way down the bottom:

button[disabled]:active, button[disabled],
input[type="reset"][disabled]:active,
input[type="reset"][disabled],
input[type="button"][disabled]:active,
input[type="button"][disabled],
select[disabled] > input[type="button"],
select[disabled] > input[type="button"]:active,
input[type="submit"][disabled]:active,
input[type="submit"][disabled] {
  padding: 0px 6px 0px 6px;
  border: 2px outset buttonface;
  color: graytext;
  cursor: inherit;
}

graytext is actually a system color – it’s defined by the css 2.1 specification and supported on and off in various browsers. these “special” color keywords are supposed to match the local system styles – on a windows machine, for instance, firefox would use the color: graytext rule to style text in disabled fields with the same color that the local windows system uses. a list of options is available on the css reference as well.