12

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?

5 Answers5

1

Try this code :

select > option[value=""]{
     color: gray;
}
Purvi Barot
  • 608
  • 3
  • 9
1

You can use pseudo classes :first-child, :nth-child(1), :nth-of-type(1), if your empty option always will be on the first position. As I understand, option with empty value and text "Select" should be first, as default. In this case, we will be aware that.

Ivan Kharkovsky
  • 446
  • 3
  • 15
1

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;
}
run_the_race
  • 1,774
  • 2
  • 25
  • 33
0
<select name="backGround" size="1" onChange="updateTextColour(this.value);"><!--changeColor(this.selected);"-->
            <option style="color:Gray">Select</option>
            <option style="color:Black">Value 1</option>
            <option style="color:Black">Value 2</option>
</option>
        </select></span></span></td>
user1647667
  • 1,269
  • 4
  • 13
  • 26
0

Sweet and Simple, Just add below CSS will resolve your issue. I hope it'll help you out.

select option[value=""] {
  color: red;
}
  • Verified on Google Chrome: Version 92.0.4515.107 (Official Build) (64-bit)
  • Verified on Firefow: Version 90.0.2 (64-bit)

select option[value=""] {
  color: red;
}
<select>
    <option value="">Select</option>
    <option value="1">One</option>
    <option value="2">Two</option>    
</select>

<select>
    <option value="">Select</option>
    <option value="1">One</option>
    <option value="">Two</option>  
    <option value="3">Three</option>  
    <option value="">Four</option>  
</select>
Hassan Siddiqui
  • 2,728
  • 1
  • 12
  • 21