Disable a textbox using CSS

How to disable a textbox in CSS? Currently we are having a textbox in our view which can be enabled/disabled depending on a property in the model. We are having asp.net MVC view; depending on the value of the Model property we need to either render a textbox or readonly textbox. we were thinking of doing this by applying CSS to the view control. Has someone done this earlier?


you can disable via css:

pointer-events: none; 

Doesn't work everywhere though.


CSS cannot disable the textbox, you can however turn off display or visibility.

display: none;
visibility: hidden;

Or you can also set the HTMLattribute:

disabled="disabled"

You can't disable anything with CSS, that's a functional-issue. CSS is meant for design-issues. You could give the impression of a textbox being disabled, by setting washed-out colors on it.

To actually disable the element, you should use the disabled boolean attribute:

<input type="text" name="lname" disabled />

Demo: http://jsfiddle.net/p6rja/

Or, if you like, you can set this via JavaScript:

document.forms['formName']['inputName'].disabled = true;​​​​

Demo: http://jsfiddle.net/655Su/

Keep in mind that disabled inputs won't pass their values through when you post data back to the server. If you want to hold the data, but disallow to directly edit it, you may be interested in setting it to readonly instead.

// Similar to <input value="Read-only" readonly>
document.forms['formName']['inputName'].readOnly = true;

Demo: http://jsfiddle.net/655Su/1/

This doesn't change the UI of the element, so you would need to do that yourself:

input[readonly] { 
    background: #CCC; 
    color: #333; 
    border: 1px solid #666 
}

You could also target any disabled element:

input[disabled] { /* styles */ }

You can't disable a textbox in CSS. Disabling it is not a presentational task, you will have to do this in the HTML markup using the disabled attribute.

You may be able to put something together by putting the textbox underneath an absolutely positioned transparent element with z-index... But that's just silly, plus you would need a second HTML element anyway.

You can, however, style disabled text boxes (if that's what you mean) in CSS using

input[disabled] { ... }

from IE7 upwards and in all other major browsers.