Ace
Ace

Reputation: 710

Applying css for the disabled option when optgroup not present

I have a select component with grouped options and another default option. The CSS isn't getting applied to the option without the group.

The option that is hidden disabled, I would like to change the color to mimic the placeholder. How can this be done?

   <select required>
        <option hidden disabled selected> -- select -- </option>
        <optgroup label="one">
            <option > A </option>
            <option > B </option>
            <option > C </option>
            <option > D </option>
        </optgroup>
        <optgroup label="two">
            <option > E </option>
            <option > F </option>
            <option > G </option>
            <option > H </option>
        </optgroup>
    </select>

option[disabled]{
  color: red;
}
<select required>
    <option hidden disabled selected> -- select -- </option>
    <optgroup label="one">
        <option > A </option>
        <option > B </option>
        <option > C </option>
        <option > D </option>
    </optgroup>
    <optgroup label="two">
        <option > E </option>
        <option > F </option>
        <option > G </option>
        <option > H </option>
    </optgroup>
</select>


Updated

The font color change is expected only initially. On change of drop-down the default color should get applied.

The hidden is used to use the option in place of the placeholder. I can not used placeholder hence, trying to mimic the behavior with this implementation.

The first-child doesn't fix the issue since the options array is dynamically created so the position may change.

Upvotes: 0

Views: 313

Answers (1)

Ace
Ace

Reputation: 710

The addition of select:required:invalid in the css and value="" for the default selected option fixed my issue.

We can use the :invalid pseudo selector when a dropdown is marked as required and the default value assigned to it is an empty string

select:required:invalid {
  color: red;
}
optgroup, option {
  color: black;
}
<select required>
    <option hidden disabled selected value=""> -- select -- </option>
    <optgroup label="one">
        <option > A </option>
        <option > B </option>
        <option > C </option>
        <option > D </option>
    </optgroup>
    <optgroup label="two">
        <option > E </option>
        <option > F </option>
        <option > G </option>
        <option > H </option>
    </optgroup>
</select>

Upvotes: 0

Related Questions