James Morrison
James Morrison

Reputation: 2122

Styling input placeholder when input is read-only

I'm trying to style my input placeholder property only when the input is read-only but I can't seem to get the two selectors to work together, is this possible? I've tried a few variations but thought the below should work;

input:read-only + ::placeholder { color: black !important; }

...and to ensure max browser comptibility

input:read-only + ::-webkit-input-placeholder, input:read-only + ::placeholder, input:-moz-read-only + ::placeholder, input:read-only + ::-ms-input-placeholder { color: black  !important; }

None of these work, is this possible? Where am I going wrong?

Upvotes: 2

Views: 3033

Answers (2)

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use the following solution:

input[readonly]::placeholder {
  color: blue !important;
}
<input type="text" placeholder="Hey StackOverflow" readonly/>
<input type="text" placeholder="Hey StackOverflow"/>


Browser Compatibility / Can I use?


Why your CSS rules doesn't work?

Your CSS rules to format the placeholder tries to access a following placeholder (placeholder after <input> element). The placeholder is on the <input> element itself, so your rules doesn't match.

p + p {
  color:blue;
}
<p>Hello</p>
<p>StackOverflow</p>

more: Explanation of the + sign in CSS rules

Upvotes: 4

Paulie_D
Paulie_D

Reputation: 114990

The Placeholder is not a child of the input so no space is needed in the selector.

input:read-only::placeholder {
  color: red
}
<input type="text" placeholder="You can't type here!" readonly>

Upvotes: 3

Related Questions