: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-shownCSS擬似クラスで、プレイスホルダー文字列が表示されている <input> または <textarea> 要素を表します。

css
/* プレイスホルダーが有効な要素を選択 */
:placeholder-shown {
  border: 2px solid silver;
}

試してみましょう

構文

: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="Name, Rank, and Serial Number" /> <br /><br />
<input id="input2" placeholder="Name, Rank, and Serial Number" />

CSS

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

結果

カスタマイズした入力欄

以下の例では部署名と ID コード欄をカスタムスタイルで強調します。

HTML

html
<form id="test">
  <p>
    <label for="name">Enter Student Name:</label>
    <input id="name" placeholder="Student Name" />
  </p>
  <p>
    <label for="branch">Enter Student Branch:</label>
    <input id="branch" placeholder="Student Branch" />
  </p>
  <p>
    <label for="sid">Enter Student 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.

関連情報