如何为select标签内首个option设置灰色字体?CSS选择器问题
The issue with your original code is that .input select:first-child targets the <select> element itself (since it's the first child of .input), not the first <option> inside it. This applies the gray color to the entire select, which all options inherit—hence why everything looks gray.
Here's the fix, tailored for Bootstrap 4:
Step 1: Update Your HTML
Add Bootstrap's form-control class to the select (standard for Bootstrap forms) and the required attribute. The required attribute lets us target the select when the placeholder option is selected via CSS's :invalid pseudo-class:
<div class="input"> <select class="form-control" required> <option value="" selected disabled>Your interests</option> <option value="test1">Test</option> <option value="test2">Test</option> </select> </div>
Step 2: Add the Corrected CSS
We need two rules: one to gray out the first option when the dropdown is open, and another to gray out the select's displayed text when the placeholder is active:
/* Gray out the first option in the dropdown */ .input select.form-control option:first-child { color: gray; } /* Gray out the select's text when the placeholder is selected (invalid state) */ .input select.form-control:invalid { color: gray; } /* Optional: Keep the gray color when the select is focused but still on the placeholder */ .input select.form-control:focus:invalid { color: gray; }
How This Works
- The
option:first-childselector directly targets the placeholder option, making it gray only when the dropdown is open. - The
:invalidpseudo-class targets the select when the selected option has an empty value (our placeholder) and the select is marked as required. This ensures the displayed text is gray when the placeholder is active. - When the user selects a valid option (with a non-empty value), the select becomes
:valid, and Bootstrap's default text color takes over automatically.
Notes
- Make sure your non-placeholder options have non-empty
valueattributes—this is what triggers the:validstate. - The
form-controlclass is necessary to align with Bootstrap's styling and ensure your custom CSS takes precedence.
内容的提问来源于stack exchange,提问作者pagani

