0
<select>
  <option disabled selected>=select=</option>
  <option>1</option>
</select>


When the user sees 「=select=」, I want to the color is gray.
And when selected 「1」, the color is black like this image:

enter image description here

select { color: black; }

select:empty { color: gray; }
//invalid

Is it possible to change color only with css? Thanks!

Nitin Bisht
  • 5,053
  • 4
  • 14
  • 26
c j
  • 50
  • 7
  • 1
    Possible duplicate of [CSS :selected pseudo class similar to :checked, but for – Saurabh Mistry Jun 28 '18 at 09:43
  • Thank you for your share, but I did't mean the option. I add a photo to help my expression... https://i.stack.imgur.com/9hcm9.png – c j Jun 29 '18 at 01:14

1 Answers1

0

You could use a function to change the class of the select element onchange:

var myselect = document.getElementById("select1");

function colourFunction() {
  var colour = myselect.options[myselect.selectedIndex].className;
  myselect.className = colour;
}

// Call function on load:
colourFunction();
.color_gray {
  color: gray;
}

.color_black {
  color: black;
}
<select id="select1" onchange="colourFunction()">
  <option disabled selected class='color_gray'>=select=</option>
  <option class='color_black'>1</option>
</select>

Note that I also used the colored classes on the option elements. But it's not mandatory.

Hope it helps.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47