:placeholder-shown

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

:placeholder-shown CSS 伪类表示当前显示占位符文本的任何 <input><textarea> 元素。

尝试一下

语法

css
:placeholder-shown {
  /* ... */
}

示例

基础示例

该示例中,输入框在显示占位符时将应用特殊字体和边框样式。

HTML

html
<input placeholder="在这里输入一些东西!" />

CSS

css
input {
  border: 1px solid black;
  padding: 3px;
}

input:placeholder-shown {
  border-color: teal;
  color: purple;
  font-style: italic;
}

结果

文本溢出

当表单字段太小时,占位文本可能会以不良方式被裁剪。你可以使用 text-overflow 属性来更改溢出文本的显示方式。

HTML

html
<input id="input1" placeholder="名字、排行和序号" /> <br /><br />
<input id="input2" placeholder="名字、排行和序号" />

CSS

css
#input2:placeholder-shown {
  text-overflow: ellipsis;
}

结果

自定义输入框

以下示例使用自定义样式突出显示了学生 ID 字段。

HTML

html
<form id="test">
  <p>
    <label for="name">输入学生姓名:</label>
    <input id="name" placeholder="学生姓名" />
  </p>
  <p>
    <label for="branch">输入学生分会:</label>
    <input id="branch" placeholder="学生分会" />
  </p>
  <p>
    <label for="sid">输入学生 ID:</label>
    <input
      type="number"
      pattern="[0-9]{8}"
      title="8 digit ID"
      id="sid"
      class="studentid"
      placeholder="8 digit id" />
  </p>
  <input type="submit" />
</form>

CSS

css
input {
  background-color: #e8e8e8;
  color: black;
}

input.studentid:placeholder-shown {
  background-color: yellow;
  color: red;
  font-style: italic;
}

结果

规范

Specification
HTML
# selector-placeholder-shown
Selectors Level 4
# placeholder-shown-pseudo

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:placeholder-shown
Support on non-type="text" elements (such as type="number" or type="time")

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Uses a non-standard name.
Has more compatibility info.

参见