简体   繁体   中英

How to apply background color to only selected option in select tag

I can't set background-color of a selected option in a drop-down list. My working is:

<select name="Occupancy Status" class="form-control form-control-sm">
    <option style="background-color:#333333" selected>Select your Occupany Status</option>
    <option>bla bla</option>
    <option>bla bla</option>
    <option>bla bla</option>                       
</select>

Is there a way to achieve desired output? Thank you.

The :checked pseudo-class in CSS initially applies to such elements that have the HTML4 selected and checked attributes. This change the style of selected option from dropdown list. Also if you want to default the styling to unselected options you can just use :not() property.


option:not(:checked) {
  /*Your Styling Here*/
}

Here's a Working code:

 option:checked { background-color: #333; color: #fff; }
 <select name="Occupancy Status" class="form-control form-control-sm"> <option selected>Select your Occupany Status</option> <option>bla bla</option> <option>bla bla</option> <option>bla bla</option> </select>

Is this what you are looking for? It isn't polished at all just wanted to see if this is the basic behavior that you're describing that you can't figure out.

 .form { height: 50vh; width: 50vw; background: #333; color: #fff; margin: 0 auto; padding: 2rem; } .field-select { border-radius: 5px; background-color: transparent; border-color: rgba(255, 255, 255, 0.25); color: #fff; } .field-select > option { color: initial !important; }
 <div class="form"> <div class="field"> <label>What is your house type? <span>(Required)</span></label> <div> <select class="field-select" aria-required="true" aria-invalid="false"> <option value="" selected="selected" class="field-placeholder">Select</option> <option value="Detached House">Detached House</option> <option value="Semi-Detached House">Semi-Detached House</option> <option value="Mid-Terrace House">Mid-Terrace House</option> <option value="End-Terrace House">End-Terrace House</option> <option value="Detached Bungalow">Detached Bungalow</option> <option value="Semi-Detached Bungalow">Semi-Detached Bungalow</option> <option value="Flat">Flat</option> <option value="Other">Other</option> </select> </div> </div> </div>

Hit run code snippet aove, or check out on my CodePen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM