Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 595
Matteo NNZ Avatar asked Feb 07 '15 22:02

Matteo NNZ


People also ask

How do I change the color of a selection in CSS?

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;" .

Can you style a select tag?

<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.

How do you change the selected text color?

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.

How do you select text in CSS?

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.


1 Answers

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

like image 174
msfoster Avatar answered Oct 03 '22 08:10

msfoster