How to change select box option background color?

2018-12-31 22:19发布

I have a Select Box and I'm trying to change the background color of the options when the Select box has been clicked and shows all the options.

See Fiddle

html

<select>
    <option val="">Please choose</option>
    <option val="1">Option 1</option>
    <option val="2">Option 2</option>
    <option val="3">Option 3</option>
    <option val="4">Option 4</option>
</select>

css

select{
    margin:40px;
    background: rgba(0,0,0,0.3);
    color:#fff;
    text-shadow:0 1px 0 rgba(0,0,0,0.4);
}

10条回答
旧人旧事旧时光
2楼-- · 2018-12-31 22:46
$htmlIngressCss='<style>';
$multiOptions = array("" => "All");
$resIn = $this->commonDB->getIngressTrunk();
while ($row = $resIn->fetch()) {
    if($row['IsActive']==0){
        $htmlIngressCss .= '.ingressClass select, option[value="'.$row['TrunkInfoID'].'"] {color:red;font-weight:bold;}';
    }
    $multiOptions[$row['TrunkInfoID']] = $row['IngressTrunkName'];
}
$htmlIngressCss.='</style>';

add $htmlIngressCss in your html portion :)

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 22:54

Another option is to use Javascript:

if (document.getElementById('selectID').value == '1') {
       document.getElementById('optionID').style.color = '#000';

(Not as clean as the CSS attribute selector, but more powerful)

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 22:57

If you really want to style the within a , consider switching to a Javascript/CSS based drop down such as http://getbootstrap.com/2.3.2/components.html#dropdowns or https://silviomoreto.github.io/bootstrap-select/examples/. This because browsers such as IE do not allow styling of options within elements. Chrome/OSX also has this problem - you cannot style options.

However a warning is attached to that approach. These types of menus work very differently on mobile platforms because native elements aren't used. They can have annoying quirks on desktop as well. My advice is 1) don't write your own and 2) find a library that's been really well tested.

查看更多
孤独寂梦人
5楼-- · 2018-12-31 23:00

My selects would not color the background until I added !important to the style.

    input, select, select option{background-color:#FFE !important}
查看更多
宁负流年不负卿
6楼-- · 2018-12-31 23:01

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

查看更多
看风景的人
7楼-- · 2018-12-31 23:02

Simply change bg color

select { background: #6ac17a; color:#fff; }

查看更多
登录 后发表回答