To create a placeholder for a <select>
dropdown (like “Choose an option…”), use the following HTML and CSS:
HTML
<select required>
<option value="" disabled selected hidden>Choose an option...</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Key Attributes
disabled
: Prevents selecting the placeholder.selected
: Shows the placeholder by default.hidden
: Hides the placeholder from the dropdown list (modern browsers).value=""
: Ensures the placeholder isn’t submitted with the form.required
: Forces the user to pick a valid option.
CSS (Optional Styling)
Gray out the placeholder text:
select:invalid {
color: #999; /* Placeholder text color */
}
select option {
color: #000; /* Regular option text color */
}
select option[disabled][hidden] {
display: none; /* Hide placeholder in older browsers */
}
How It Works
- The placeholder appears by default but can’t be selected (
disabled
). - The
required
attribute ensures a valid option is chosen. - The
hidden
attribute hides the placeholder from the dropdown in modern browsers.
Browser Compatibility
- Modern Browsers (Chrome, Firefox, Edge):
Hides the placeholder in the dropdown withhidden
. - Legacy Browsers (IE, older Safari):
The placeholder may appear in the dropdown but remains unselectable (disabled
).
Example with Validation
<form>
<select required>
<option value="" disabled selected hidden>Select a country...</option>
<option value="us">United States</option>
<option value="ca">Canada</option>
</select>
<button type="submit">Submit</button>
</form>
- Submitting without selecting a valid option triggers browser validation.
JavaScript Alternative
Dynamically add/remove the placeholder:
const select = document.querySelector('select');
// Show placeholder initially
select.innerHTML = '<option value="" disabled selected hidden>Choose...</option>' + select.innerHTML;
// Remove placeholder on focus
select.addEventListener('focus', () => {
if (select.value === "") {
select.querySelector('option[disabled]').remove();
}
});
Summary
Use the HTML-only method for simplicity, or combine with CSS/JavaScript for enhanced UX.