Home > Net >  Change the select text color based on option color
Change the select text color based on option color

Time:01-13

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

CodePudding user response:

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>

CodePudding user response:

This won't be possible with just CSS, you'll need a combination of both CSS and JS. The nature of CSS is to cascade down, not up, we cannot affect the parent element (the select field here) when something happens to a child element(the option).

CodePudding user response:

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" >Blue</option>
  <option value="2" >Red</option>
</select>

  •  Tags:  
  • css
  • Related