Explain Codes LogoExplain Codes Logo

How to style readonly attribute with CSS?

html
css
readonly
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Jul 22, 2024
TLDR

To style readonly inputs with CSS, target the attribute [readonly]:

input[readonly] { background: #e0e0e0; color: #6d6d6d; }

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:

input:read-only { border: 2px dashed #9e9e9e; /* It's like a "Do Not Cross" line for inputs */ }

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:

input[readonly], input:read-only { outline: none; cursor: not-allowed; /* Not today, user ✋ */ }

Advanced selector tactics

Exclude erroneous false declarations

JavaScript might mistakenly mark readonly="false". To handle this, we introduce another excellent trick:

input:read-only:not([readonly="false"]) { background-color: #f7f7f7; /* We got you covered, rogue JavaScript */ }

Styling textarea and other input types

The readonly attribute is used not only in input, but also in elements like textarea. Consistency is key:

textarea[readonly] { opacity: 0.5; /* Ghostly 😱 */ }

And feel free to style specific types of inputs:

input[type='text']:read-only, input[type='email']:read-only { background-color: #f0f0f0; /* Cool as a cucumber */ }

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:

/* For Firefox, with love ❤️ */ input:-moz-read-only { box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1); /* Like a soft-glow lamp. Subtle, yet distinct */ }

HTML vs JavaScript

Boolean attributes in HTML

In HTML, it's preferred to be explicit with readonly="readonly":

<input type="text" name="example" readonly="readonly"> /* Good ol' HTML, you relish clarity */

JavaScript dynamic styles

And when dealing with dynamic attribute changes via JavaScript, do this:

// When JavaScript decides to be busy with attributes document.getElementById('myInput').setAttribute('readonly', 'readonly');
/* The CSS magic wand reacts */ [readonly] { cursor: default; /* Because a pointing hand suggests mischief */ }