You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为select标签内首个option设置灰色字体?CSS选择器问题

Correct CSS to Style Only the First Option in a Select (Bootstrap 4)

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-child selector directly targets the placeholder option, making it gray only when the dropdown is open.
  • The :invalid pseudo-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 value attributes—this is what triggers the :valid state.
  • The form-control class is necessary to align with Bootstrap's styling and ensure your custom CSS takes precedence.

内容的提问来源于stack exchange,提问作者pagani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:01:49