3

I want to display the selected option in the same colour as the option itself.

<select>
  <option value="1" style="color:blue">Blue</option>
  <option value="2" style="color:red">Red</option>
</select>

The options are displayed correctly in blue and red colours, but once selected, they are black. Is it possible to display it in blue or red, matching the selected option?

PD: I know how to do it in JS, but I'm not sure if it could be done in CSS

joseantgv
  • 1,943
  • 1
  • 26
  • 34

2 Answers2

2

This can be done with pure CSS with the :has pseudo class

select:has(option[value="1"]:checked) {
  color: blue;
}
select:has(option[value="2"]:checked) {
  color: red;
}
<select>
  <option value="1">Blue</option>
  <option value="2">Red</option>
</select>
Danield
  • 121,619
  • 37
  • 226
  • 255
0

If select has onchange it can modify dataset equal to value. Then css can reflect that. If this is part of a larger application, remove onchange and implement an event listener in js file

.blue,select[data-chosen='1']{
  color:blue;
}
.red,select[data-chosen='2']{
  color:red;
}
<select onchange="this.dataset.chosen = this.value;" data-chosen="1">
  <option value="1" class="blue">Blue</option>
  <option value="2" class="red">Red</option>
</select>
depperm
  • 10,606
  • 4
  • 43
  • 67
  • Stop using inline `on*` handlers like `onchange`. JS is supposed to be in one place only and that's its respective tag or file – Roko C. Buljan Jan 12 '23 at 14:54
  • Also, if you're using JavaScript anyway you may as well just use simple CSS and - one option - [CSS custom properties](https://jsfiddle.net/davidThomas/4remaz2q/), or possibly just directly [change the color with CSS](https://jsfiddle.net/davidThomas/4remaz2q/1/). – David Thomas Jan 12 '23 at 15:01
  • @DavidThomas neither of those keep current styling, both change all options to the selected color – depperm Jan 12 '23 at 15:12
  • That's what I get for not testing in Chrome (as well as Firefox). – David Thomas Jan 12 '23 at 15:15
  • @RokoC.Buljan for the amount of js its not [horrible](https://stackoverflow.com/a/19002885/3462319) if this is a larger application, separation would be better – depperm Jan 12 '23 at 15:19
  • Casually the HTML field is repainted with an AJAX request so I couldn't use the `onchange` event, because it would be fired and then refreshed. – joseantgv Jan 13 '23 at 10:24