Search code examples
javascripthtmlcss

Changing the color of a <select> depending on its value - CSS only(?)


I have an HTML select element with some options inside:

<select class = "myRed" id="mySelect" onchange="onSelectChange()">
    <option selected value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

I would like the text color of the select object to be red when its value is 0, black otherwise. I could be able to do this through JavaScript:

function onSelectChange(){
    if (document.getElementById('mySelect').value == 0){
        document.getElementById('mySelect').className = 'myRed';
    } else {
        document.getElementById('mySelect').className = 'myBlack'
    }
}

where

.myRed{color:red;}

and

.myBlack{color:black;}

However, I've been told this is somehow reachable through CSS only, without using JavaScript. I cannot think about any other way than using JS. Could anyone please advise?


Solution

  • You can use required and assign empty value to the first option:

    <select class="mySelect" required>
        <option value="">0</option>
        <option value="1">1</option>
    </select>
    

    css:

    .mySelect { font-size: 2em; }
    .mySelect option { color: green; }
    .mySelect option[value=""] { color: red; }
    .mySelect:invalid { color: red; }
    

    Check fiddle