简体   繁体   English

如何将背景颜色应用于选择标签中的仅选定选项

[英]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. CSS 中的:checked伪类最初适用于具有 HTML4 selectedchecked属性的元素。 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.此外,如果您想将样式默认为未选择的选项,您可以使用:not()属性。


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 .点击运行代码片段,或查看我的 CodePen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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