mark mark - 6 months ago 33
CSS Question

Is it possible to make input fields read-only through CSS?

I know that input elements are made read-only by applying the

readonly
boolean attribute, and being an attribute it is not affected by CSS.

On the other hand, my scenario seems to be a very good fit for CSS, so I was hoping there is some kind of a CSS trick to let me do it. I have a printable version hyperlink on my form. Clicking it displays a ... printable version of the document. It is mostly CSS stuff, my print.css looks like this:

html.print {
width: 8.57in;
}

.print body {
font: 9pt/1.5 Arial, sans-serif;
margin: 0 1in;
overflow: auto;
}

.print #header, .print #footer {
display: none;
}

.print .content {
background-color: white;
overflow: auto;
}

.print .fieldset > div.legend:first-child {
background: white;
}

.print ::-webkit-input-placeholder {
/* WebKit browsers */
color: transparent;
}

.print :-moz-placeholder {
/* Mozilla Firefox 4 to 18 */
color: transparent;
}

.print ::-moz-placeholder {
/* Mozilla Firefox 19+ */
color: transparent;
}

.print :-ms-input-placeholder {
/* Internet Explorer 10+ */
color: transparent;
}

.print .check-mark {
display: inline;
}

.print input[type=checkbox] {
display: none;
}

.print .boolean-false {
display: none;
}


There are also a few javascript pieces, such as:


  • Adding the
    print
    class to the html element

  • Displaying tables without scroll bars

  • A few other minor things, like hiding any popup overlays.



My current problem is input fields. They should be read-only, however, I have no idea how to do it with minimum changes to the code. CSS could be a perfect solution.

Any ideas?

Answer

With CSS only? This is sort of possible on text inputs by using user-select:none:

.print {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;          
}

JSFiddle example.

It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select property. The readonly property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.

With JavaScript:

document.getElementById("myReadonlyInput").setAttribute("readonly", "true");

Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select property now appears to be ignored on input elements.