Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

html - Modify Select So Only The First One Is Gray

I have a select element and am using the first option as the title of the select field. I am wondering if there is a way to gray out the text inside the select field when the first option is selected. Can this only be done in JS, or is there a CSS solution?

I have tried changing the style of the first option but that only changes the colour of the text when I activate the dropdown menu.

<select>
  <option>Please select your favourite fruit</option>
  <option>Apple</option>
  <option>Banana</option>
</select>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a more modern solution so it's not specific to the first option, but rather an invalid option and requires no JS to show only the title/placeholder option as grey whereas the rest appear normal.

select,
select option {
  color: #000000;
}

select:invalid,
select option[value=""] {
  color: #999999;
}

label {
  display: block;
  margin: 16px 0;
}

/*Added for browser compatibility*/
[hidden] {
  display: none;
}
<label>
    Invalid option cannot be selected and is hidden from the user in the dropdown.
    <select required>
      <option value="" selected disabled hidden>Please select your favourite fruit</option>
      <option>Apple</option>
      <option>Banana</option>
    </select>
</label>

<label>
    Invalid option cannot be selected, but is not hidden from the user in the dropdown.
    <select required>
      <option value="" selected disabled>Please select your favourite fruit</option>
      <option>Apple</option>
      <option>Banana</option>
    </select>
</label>

<label>
    Invalid option can be selected and is not hidden from the user in the dropdown.
    <select required>
      <option value="" selected>Please select your favourite fruit</option>
      <option>Apple</option>
      <option>Banana</option>
    </select>
</label>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...