Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style select dropdown only when value is empty

Tags:

html

css

Lets say I have markup like this:

<select>
    <option value="">Select</option>
    <option value="1">One</option>
    <option value="2">Two</option>    
</select>

Now, I want the dropdown to display in gray ONLY when the value is empty i.e when it is showing "Select". When the user has selected one of the options, it should be black / default color.

(This is to be visually consistent with textboxes on my page that have gray placeholders).

I want to accomplish something like this:

select[value=""] {
    color: gray;
}

But it turns out that the select tag doesn't really have a value attribute.

Any way to accomplish this other than using JavaScript?

like image 614
Natarajan Shanker Avatar asked Mar 10 '14 05:03

Natarajan Shanker


1 Answers

Styling options, will only style them as shown in the drop down list, not when the select is not in focus. I wanted the select to be italic when the blank option is shown, it can be achived like this:

/* If the select does not have a valid value, ie the blank option is selected, we make it italic */
select:invalid {
    font-style: italic;
}

/* Now the child options inherit the italics style, so we reset that*/
select > option {
    font-style: normal;
}

/* Apply italics to the invalid options too when shown in the dropdown */
select option[value=""], select option:not([value]) {
    font-style: italic;
}
like image 192
run_the_race Avatar answered Oct 27 '22 00:10

run_the_race