How to add and style a field hint (placeholder)
Short answer
The placeholder attribute sets the hint text inside an empty field, and the ::placeholder pseudo-element sets its look:
<style>
input { padding: 8px; }
input::placeholder { color: slategray; font-style: italic; }
</style>
<input type="email" placeholder="anna@example.com">The hint disappears as soon as the user starts typing.
What to write in the hint
Best of all — a sample value or a format: anna@example.com, DD.MM.YYYY. Put the field name and important rules in the label above the field, otherwise the user will not see them after starting to type:
<label style="display: grid; gap: 4px; max-width: 260px;">
Date of birth
<input type="text" placeholder="DD.MM.YYYY" style="padding: 8px;">
</label>An empty field in CSS
The :placeholder-shown pseudo-class fires while the hint is visible, that is, while the field is empty. "Floating" labels that shrink and move up while typing are built on it.
Common mistake
The hint is used instead of a label: a field without <label>, and the name only in placeholder. Once the user starts typing, it is no longer clear what the field was. Many screen readers also do not read the hint as the name. Besides, light gray text is often too pale to read.
<input placeholder="Name"> <input placeholder="Surname">Functions used in this recipe
- placeholder — A hint or example inside an empty field.
- ::placeholder — The placeholder text of a field — the hint from the `placeholder` attribute.
- <label> — A label for a form field.
- <input> — An input field; its kind is set by the `type` attribute.