1. 開発者向けのウェブ技術
  2. CSS
  3. リファレンス
  4. セレクター
  5. :placeholder-shown

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

: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 ⁨2020年1月⁩.

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

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

試してみましょう

label {
 display: block;
 margin-top: 1em;
}
input:placeholder-shown {
 background-color: ivory;
 border: 2px solid darkorange;
 border-radius: 5px;
}
<form>
 <label for="name">Full Name:</label>
 <input id="name" name="name" type="text" />
 <label for="email">Email Address:</label>
 <input id="email" name="email" type="email" placeholder="name@example.com" />
 <label for="age">Your age:</label>
 <input
 id="age"
 name="age"
 type="number"
 value="18"
 placeholder="You must be 18+" />
</form>

構文

: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

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /