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?
To change the selected option background-color CSS style, we can set the style attribute of the select and option elements. to set the whole select element to background color 009966 and color FFF . Then we override the the styles in the option elements with style="background: white; color: black;" .
<select> tags can be styled through CSS just like any other HTML element on an HTML page rendered in a browser. Below is an (overly simple) example that will position a select element on the page and render the text of the options in blue.
The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.
The ::selection selector matches the portion of an element that is selected by a user. Only a few CSS properties can be applied to the ::selection selector: color, background, cursor, and outline.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With