CSS :read-only

The CSS :read-only pseudo-class is used when we need to select and style an element with the READONLY attribute. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      input:read-only {background-color: #ccc;}
   </style>
</head>
<body>

   <form>
      Username: <input type="text"><br/><br/>
      Password: <input type="password"><br/><br/>
      Country: <input readonly value="Netherlands">
   </form>
   
</body>
</html>
Output
Username:

Password:

Country:

This example defines a CSS rule that uses the :read-only pseudo-class to select and style any input element that has the readonly attribute set to true. The rule changes the input field's background color to a light gray (#ccc).

Within a form element in the HTML code, there are three input fields. The first two input fields are standard text and password fields, respectively, while the third has the readonly attribute set and a default value of "Netherlands."

Because the readonly attribute is set on the third input field, it will match the CSS rule defined in the style element, and its background color will be set to a light gray color (#ccc), indicating that it cannot be edited.

Because the readonly attribute is not set on the first two input fields, they will not match the CSS rule, and their background color will remain unchanged.

Therefore, the third element, right after Country:, is read-only, meaning we cannot enter or type anything inside this field.

CSS :read-only syntax

The general form or the syntax of the ":read-only" class in CSS is:

selector:read-only {
  // styles to be applied to read-only elements
}

"selector" in the syntax above can be any valid CSS selector that targets the desired read-only elements, such as input:read-only to select all read-only input fields.

Advantages of the ":read-only" class in CSS

Disadvantages of the ":read-only" class in CSS

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!