试一试
input {
margin-top: 0.5rem;
}
input::placeholder {
font-weight: bold;
opacity: 0.5;
color: red;
}
<label for="first-name">Your phone number:</label><br />
<input
id="first-name"
type="tel"
name="phone"
minlength="9"
maxlength="9"
placeholder="It must be 9 digits" />
只有适用于 ::first-line 伪元素的 CSS 属性子集才能在选择器中使用 ::placeholder 的规则中使用。
注意:在大多数浏览器中,占位符文本的默认外观是半透明或浅灰色。
语法
::placeholder {
/* ... */
}
无障碍
颜色对比度
对比度
占位符文本通常采用较浅的颜色处理,以表明它是一种关于何种输入有效的建议,而不是任何实际输入。
重要的是要确保占位符文本颜色与输入背景之间的对比度足够高,以便视力低下的人能够阅读它,同时还要确保占位符文本和输入文本颜色之间有足够的差异,以避免用户将占位符误认为已输入数据。
颜色对比度是通过比较占位符文本和输入背景颜色值的亮度来确定的。为了满足当前的Web 内容可访问性指南 (WCAG),文本内容的比例要求为 4.5:1,对于标题等较大文本则为 3:1。大文本定义为 18.66px 及以上粗体或更大,或 24px 或更大。
可用性
具有足够颜色对比度的占位符文本可能会被解释为已输入内容。当用户在 <input> 元素中输入内容时,占位符文本也会消失。这两种情况都可能干扰表单成功完成,尤其是对于有认知障碍的人。
提供占位符信息的另一种方法是将其放在输入框外部,靠近视觉,然后使用 aria-describedby 以编程方式将 <input> 与其提示关联起来。
通过这种实现,即使在输入字段中输入了信息,提示内容仍然可用,并且当页面加载时,输入框看起来没有预先存在的输入。大多数屏幕阅读技术将使用 aria-describedby 在宣布输入标签文本后读取提示,如果屏幕阅读器用户觉得额外的信息不必要,他们可以将其静音。
<label for="user-email">Your email address</label>
<span id="user-email-hint" class="input-hint">Example: jane@sample.com</span>
<input
id="user-email"
aria-describedby="user-email-hint"
name="email"
type="email" />
Windows 高对比度模式
在Windows 高对比度模式下渲染时,占位符文本将与用户输入的文本内容具有相同的样式。这将使某些人难以区分哪些内容已输入,哪些内容是占位符文本。
标签
占位符不能替代 <label> 元素。如果没有使用 for 和 id 属性的组合以编程方式与输入关联的标签,辅助技术(如屏幕阅读器)无法解析 <input> 元素。
示例
更改占位符外观
此示例展示了您可以对占位符文本样式进行的一些调整。
HTML
<input placeholder="Type here" />
CSS
input::placeholder {
color: red;
font-size: 1.2em;
font-style: italic;
opacity: 0.5;
}
结果
不透明文本
某些浏览器会使占位符文本不那么不透明。如果您想要完全不透明的文本,请明确设置 color 属性值。可以使用 currentColor 值来使其与相应的输入元素具有相同的颜色。
HTML
<input placeholder="Color set by browser" />
<input placeholder="Same color as input" class="explicit-color" />
<input placeholder="Semi-opaque text color" class="opacity-change" />
CSS
input {
font-weight: bold;
color: green;
}
.explicit-color::placeholder {
/* use the same color as input element to avoid the browser set default color */
color: currentColor;
}
.opacity-change::placeholder {
/* less opaque text */
color: color-mix(in srgb, currentColor 70%, transparent);
}
结果
注意:请注意,浏览器对占位符文本使用不同的默认颜色。例如,Firefox 使用输入元素的颜色和 54% 的不透明度,而 Chrome 使用 darkgray 颜色。如果希望在不同浏览器中保持一致的占位符文本颜色,请明确设置 color。
规范
| 规范 |
|---|
| CSS 伪元素模块 Level 4 # placeholder-pseudo |
浏览器兼容性
加载中…
另见
:placeholder-shown伪类样式化具有活动占位符的元素。- 相关 HTML 元素:
<input>、<textarea> - HTML 表单