Kaladin
Kaladin

Reputation: 33

How to change the style of a <select> after an option has been selected?

I have tried: active, focus, focus-within, target, hover, visited, focus-visible and none of them work. I want the select border to look the same. Currently it seems to get a larger border until something else is clicked.

Upvotes: 3

Views: 3591

Answers (2)

qubodup
qubodup

Reputation: 9633

Try combining select:has() and option:checked for a CSS-only solution:

select:has(option[value="1"]:checked)

Note that this will also paint all child <option> elements, so you will want to style them either all or individually. Below example styles the first 3 options individually with the same color that they set the <select> element to and the other two generally:

preview of below code on Chrome 120.0.6099.218 on Win10

option { background-color: white; }
select:has(option[value="1"]:checked), option[value="1"] { background-color: LightSalmon; }
select:has(option[value="2"]:checked), option[value="2"] { background-color: PaleGreen; }
select:has(option[value="3"]:checked), option[value="3"] { background-color: PaleTurquoise; }
select:has(option[value="4"]:checked) { background-color: grey; }
<select>
    <option value="1">Beautiful</option>
    <option value="2">Also nice</option>
    <option value="3">But how about this</option>
    <option value="4">Bland</option>
    <option value="5">Boring</option>
</select>

Upvotes: -1

Peneh
Peneh

Reputation: 315

Try

select[data-chosen]

select[data-chosen] {outline-offset:2px;outline:12px solid;}
select[data-chosen='opt1'] {outline:none;}
select[data-chosen='opt2'] {outline-color:green;}
select[data-chosen='opt3'] {outline-color:red;}
select[data-chosen='opt4'] {outline-color:steelblue;}
select[data-chosen='opt5'] {outline-color:orange;}
<select onchange=" this.dataset.chosen = this.value; ">
    <option value="opt1"> I have no outline.            </option>
    <option value="opt2"> Make it green!                </option>
    <option value="opt3"> Why not red instead!          </option>
    <option value="opt4"> No, steelblue! It's so cool!  </option>
    <option value="opt5"> Okay, orange. It's final.     </option>
</select>

Upvotes: 2

Related Questions