Question

I would like to make a HTML input field readonly but without getting the grey background that appears when I just add the attribute readonly (it should look the same as a normal field just not allow editing).

Is there a way I can realise this in CSS and/or JS, ideally with a class ?

Example field:

<input type="text" style="width:96%" class="myClass" />
Was it helpful?

Solution 2

Yes, you can use the :disabled pseudo class, e.g.

input.myClass:disabled {
    /* style declaration here */
}

OTHER TIPS

I think you mistook disabled and readonly

<input type="text" value="readonly" readonly>
<input type="text" value="disabled" disabled>

have a look to this fiddle : http://jsfiddle.net/36UwE/

As you can see, only the disabled input is grey (tested on Windows with latest Chrome & IE)

However, this may differ, according the browser, operating system and so on. You can use custom the display with css:

input[readonly] {
  background-color: white;
}
<input type="text" class="form-control" value="MyText" readonly />

<style>
    input.form-control:read-only {
        background-color: #fff;
    }
</style>

or

<input type="text" class="form-control" value="MyText" style="background-color: #fff;" readonly />

More info here.

While you can apply any styling using :disabled, :readonly or .myClass CSS selectors, be aware that different browsers/platforms will render the standard, readonly & disabled input fields differently, so trying to override color, borders and background based on the defaults for your platform (e.g. Windows) might break the styling on other platforms (e.g. Mac).

It's usually not a good idea to override the default styling cues that users expect, but if you must do this then you should ensure that readonly/disabled input fields are visually discernible from standard ones, and use custom styling that is not platform-specific.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top