joseantgv
joseantgv

Reputation: 2023

Change the select text color based on option color

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

Upvotes: 3

Views: 231

Answers (2)

depperm
depperm

Reputation: 10746

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>

Upvotes: 0

Danield
Danield

Reputation: 125443

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>

Upvotes: 2

Related Questions