Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if an <option> has been selected in <select> using CSS

I use input:not(:placeholder-shown) to determine if a value is in an input field.

Is there some CSS way to check if an <option /> has been selected in a <select> element?

I want to style the label tag immediately following the select dropdown IF an option has been selected.

Here is an example:

<select class="form-control">
    <option></option>
    <option value="1">One</option>
</select>
<label>Pick One</label>

Here is the CSS that I want to use to manipulate if an option (with a value) has been selected.

select.form-control:checked ~ label{
  color: red;
}
like image 770
Steve Lloyd Avatar asked Dec 18 '22 18:12

Steve Lloyd


2 Answers

Yes, the :checked pseudo-class also targets <option> tags.

Example:

option:checked { display:none; }

Source:

http://www.w3.org/TR/selectors/#checked

EDIT:

If you want to target an element outside of your <select>, it can be done in a hacky way by manipulating the :valid css pseudo-class. Note that the required attribute must be enabled for the <select> tag to register as valid/invalid.

Example:

body {
  background-color: #fff;
}

select:valid ~ label {
  background-color: red;
}
<select required>
  <option value="" selected>Please select an option</option>
  <option>1</option>
  <option>2</option>
</select>
<label>Please select an option</label>
like image 159
Hybrid Avatar answered Jan 05 '23 16:01

Hybrid


Since your select element doesn't have a multiple attribute, it isn't possible for an option not to be selected in it. (Yes, your option with no content and no value is still an option, can be selected, and is selected by default).

If it did, then what you want still wouldn't be possible. The :checked property would apply to the <option> elements, but you couldn't use it to target the <select> because CSS has no parent selector.

like image 41
Quentin Avatar answered Jan 05 '23 16:01

Quentin