How to style readonly attribute with CSS?
To style readonly
inputs with CSS, target the attribute [readonly]
:
This simple snippet provides a visual distinctiveness to all readonly
inputs.
Detailed explanation
Readonly
input fields, while holding values, cannot be altered by users, differing from regular inputs. Therefore, they may require differentiating visual styles to communicate this behaviour to the user.
Using the Pseudo-class :read-only
The :read-only
pseudo-class is an excellent tool to target inputs marked as readonly, as shown below:
However, remember the :read-only
pseudo-class is not supported by IE. Don't fret! For cross-browser compatibility, we can gracefully degrade to the attribute selector:
Advanced selector tactics
Exclude erroneous false
declarations
JavaScript might mistakenly mark readonly="false"
. To handle this, we introduce another excellent trick:
Styling textarea
and other input types
The readonly
attribute is used not only in input
, but also in elements like textarea
. Consistency is key:
And feel free to style specific types of inputs:
Handling browser compatibility issues
Caring for the seniors (aka old browsers)
As :read-only
is a newcomer, older browsers like IE don't support this cool kid. However, there's a fallback plan:
- Use the
[readonly]
attribute selector - If the need arises, resort to JavaScript-based polyfills
Firefox peculiarities
For Firefox, there's a special pseudo-class: :-moz-read-only
:
HTML vs JavaScript
Boolean attributes in HTML
In HTML, it's preferred to be explicit with readonly="readonly"
:
JavaScript dynamic styles
And when dealing with dynamic attribute changes via JavaScript, do this:
Was this article helpful?