输入为只读时设置输入占位符的样式

时间:2019-01-23 14:41:04

标签: css css3 css-selectors

仅在输入为只读但我似乎无法使两个选择器一起工作时,我才尝试为输入占位符属性设置样式。我尝试了一些变体,但认为以下应该可行;

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

...并确保最大程度的浏览器兼容性

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

这些工作都不可行吗?我要去哪里错了?

2 个答案:

答案 0 :(得分:3)

占位符不是input的子元素,因此选择器中不需要空格。

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

答案 1 :(得分:3)

您可以使用以下解决方案:

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


浏览器兼容性/我可以使用吗?


为什么CSS规则不起作用?

您用于格式化占位符的CSS规则尝试访问以下占位符(<input>元素之后的占位符)。占位符位于<input>元素本身上,因此您的规则不匹配。

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

更多Explanation of the + sign in CSS rules

相关问题