2

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?

James Morrison
  • 1,954
  • 2
  • 21
  • 48

2 Answers2

4

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

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
  • That's got it, thanks! Do you know what the browser compatible versions are? I tried editing all versions of the selector but it breaks them all (eg input[-moz-readonly]::placeholder, input[readonly]::-ms-input-placeholder) – James Morrison Jan 23 '19 at 15:29
3

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>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161