CSS Pseudo-Class: :read-only

The :read-only pseudo-class in CSS is used to style <input>, <textarea>, and <select> elements that cannot be modified by the user. This is particularly useful for displaying fields that provide information but should not be editable by users. Let's explore how to use this pseudo-class with examples.


/* CSS */
input:read-only {
    background-color: #e0e0e0; /* Light gray for read-only input */
    color: #666; /* Dark gray text color */
}

textarea:read-only {
    background-color: #f0f0f0; /* Light gray for read-only textarea */
    color: #999; /* Lighter gray text color */
}
Result:



In this example, we have styled read-only <input> and <textarea> elements with different background and text colors to signify that they are not editable. The background-color property is used to distinguish the read-only fields visually.

Example Breakdown

Let's analyze the code step by step:


/* CSS Styling */
input:read-only {
    background-color: #e0e0e0;
}
textarea:read-only {
    background-color: #f0f0f0;
}

/* HTML Code */
<input type="text" value="This is read-only" readonly>
<textarea readonly>This text cannot be changed.</textarea>
Result:

Conclusion

The :read-only pseudo-class is a powerful tool to enhance user experience by visually indicating which fields are not meant to be edited. Use it wisely to guide your users in forms and applications.