: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.

La pseudo-classe :placeholder-shown permet de représenter n'importe quel élément <input> ou <textarea> affichant un texte de substitution.

css
/* Cible tout élément <input> ou <textarea> avec un */
/* attribut placeholder actuellement affiché        */
:placeholder-shown {
  border: 2px solid silver;
}

Syntaxe

Error: could not find syntax for this item

Exemples

Exemple simple

CSS

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

:placeholder-shown {
  border-color: silver;
}

HTML

html
<input placeholder="Saisir quelque chose ici" />

Résultat

Dépassement du texte

Sur certains écrans plus étroits (tels que ceux des smartphones), la largeur des boîtes de recherche et celle des champs de formulaire peut être réduite fortement. Le texte de substitution peut donc être tronqué de façon indésirable. On peut alors utiliser text-overflow pour gérer cela gracieusement.

HTML

html
<input
  placeholder="Veuillez saisir quelque chose dans ce champ s'il vous plaît !" />

CSS

css
input:placeholder-shown {
  text-overflow: ellipsis;
}

Résultat

Texte coloré

HTML

html
<input placeholder="Saisir quelque chose ici" />

CSS

css
input:placeholder-shown {
  color: red;
  font-style: italic;
}

Résultat

Champ de saisie personnalisé

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;
}

Résultat

Spécifications

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

Compatibilité des navigateurs

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.

Voir aussi