如何设置 html“选择”元素的选项的样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7208786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:18:22  来源:igfitidea点击:

How to style the option of an html "select" element?

htmlcssdrop-down-menu

提问by MrClan

Here's my HTML:

这是我的 HTML:

<select id="ddlProducts" name="ddProducts"> 
    <option>Product1 : Electronics </option>
    <option>Product2 : Sports </option>
</select>

I want to make the name of the product (i.e. 'Product1', 'Product2' , etc) bold, and its categories(viz. Electronics, Sports, etc) italicized, using CSS only. I found an old question that mentioned it's not possible using HTML and CSS, but hopefully, there's a solution now.

我想将产品的名称(即 'Product1'、'Product2' 等)加粗,并将其类别(即电子、体育等)设为斜体,仅使用 CSS。我发现了一个老问题,提到不可能使用 HTML 和 CSS,但希望现在有解决方案。

采纳答案by Diodeus - James MacFarlane

There are only a few style attributes that can be applied to an <option>element.

只有少数样式属性可以应用于<option>元素。

This is because this type of element is an example of a "replaced element". They are OS-dependent and are not part of the HTML/browser. It cannot be styled via CSS.

这是因为这种类型的元素是“替换元素”的一个例子。它们依赖于操作系统并且不是 HTML/浏览器的一部分。它不能通过CSS.

There are replacement plug-ins/libraries that look like a <select>but are actually composed of regular HTMLelements that CANbe styled.

有更换插件/库看起来像<select>,但实际上是由正规的HTML那个元素CAN样式。

回答by esqew

No, it's not possible, as the styling for these elements is handled by the user's OS. MSDN will answer your question here:

不,这是不可能的,因为这些元素的样式由用户的操作系统处理。MSDN 将在这里回答您的问题

Except for background-colorand color, style settings applied through the style object for the option element are ignored.

除了background-colorand 之外color,通过 style 对象为 option 元素应用的样式设置将被忽略。

回答by Zoron19

You can style the option elements to some extent.

您可以在某种程度上设置选项元素的样式。

Using the * CSS tag you can style the options inside the box that is drawn by the system.

使用 * CSS 标签,您可以为系统绘制的框内的选项设置样式。

Example:

例子:

#ddlProducts *
{
 border-radius:15px;
 background-color:red;
}

That will look like this:

看起来像这样:

enter image description here

在此处输入图片说明

回答by Anahit Ghazaryan

I found and using this good example of styling the selects and options.You can do with this select all you want.Here is the Fiddle

我发现并使用了这个很好的例子来设置选择和选项的样式。你可以用这个选择你想要的一切。这是小提琴

html

html

<select id="selectbox1">
    <option value="">Select an option&hellip;</option>
    <option value="aye">Aye</option>
    <option value="eh">Eh</option>
    <option value="ooh">Ooh</option>
    <option value="whoop">Whoop</option>
</select>
<select id="selectbox2">
    <option value="">Month&hellip;</option>
    <option value="january">January</option>
    <option value="february">February</option>
    <option value="march">March</option>
    <option value="april">April</option>
    <option value="may">May</option>
    <option value="june">June</option>
    <option value="july">July</option>
    <option value="august">August</option>
    <option value="september">September</option>
    <option value="october">October</option>
    <option value="november">November</option>
    <option value="december">December</option>
</select>

css

css

body {
    padding:50px;
    background-color:white;
}
.s-hidden {
    visibility:hidden;
    padding-right:10px;
}
.select {
    cursor:pointer;
    display:inline-block;
    position:relative;
    font:normal 11px/22px Arial, Sans-Serif;
    color:black;
    border:1px solid #ccc;
}
.styledSelect {
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    background-color:white;
    padding:0 10px;
    font-weight:bold;
}
.styledSelect:after {
    content:"";
    width:0;
    height:0;
    border:5px solid transparent;
    border-color:black transparent transparent transparent;
    position:absolute;
    top:9px;
    right:6px;
}
.styledSelect:active, .styledSelect.active {
    background-color:#eee;
}
.options {
    display:none;
    position:absolute;
    top:100%;
    right:0;
    left:0;
    z-index:999;
    margin:0 0;
    padding:0 0;
    list-style:none;
    border:1px solid #ccc;
    background-color:white;
    -webkit-box-shadow:0 1px 2px rgba(0, 0, 0, 0.2);
    -moz-box-shadow:0 1px 2px rgba(0, 0, 0, 0.2);
    box-shadow:0 1px 2px rgba(0, 0, 0, 0.2);
}
.options li {
    padding:0 6px;
    margin:0 0;
    padding:0 10px;
}
.options li:hover {
    background-color:#39f;
    color:white;
}

JS

JS

// Iterate over each select element
$('select').each(function () {

    // Cache the number of options
    var $this = $(this),
        numberOfOptions = $(this).children('option').length;

    // Hides the select element
    $this.addClass('s-hidden');

    // Wrap the select element in a div
    $this.wrap('<div class="select"></div>');

    // Insert a styled div to sit over the top of the hidden select element
    $this.after('<div class="styledSelect"></div>');

    // Cache the styled div
    var $styledSelect = $this.next('div.styledSelect');

    // Show the first select option in the styled div
    $styledSelect.text($this.children('option').eq(0).text());

    // Insert an unordered list after the styled div and also cache the list
    var $list = $('<ul />', {
        'class': 'options'
    }).insertAfter($styledSelect);

    // Insert a list item into the unordered list for each select option
    for (var i = 0; i < numberOfOptions; i++) {
        $('<li />', {
            text: $this.children('option').eq(i).text(),
            rel: $this.children('option').eq(i).val()
        }).appendTo($list);
    }

    // Cache the list items
    var $listItems = $list.children('li');

    // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)
    $styledSelect.click(function (e) {
        e.stopPropagation();
        $('div.styledSelect.active').each(function () {
            $(this).removeClass('active').next('ul.options').hide();
        });
        $(this).toggleClass('active').next('ul.options').toggle();
    });

    // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item
    // Updates the select element to have the value of the equivalent option
    $listItems.click(function (e) {
        e.stopPropagation();
        $styledSelect.text($(this).text()).removeClass('active');
        $this.val($(this).attr('rel'));
        $list.hide();
        /* alert($this.val()); Uncomment this for demonstration! */
    });

    // Hides the unordered list when clicking outside of it
    $(document).click(function () {
        $styledSelect.removeClass('active');
        $list.hide();
    });

});

回答by Katie

Here's some ways to style <option>along with the <select>if you're using Bootstrap and/or jquery. I understand this isn't what the original poster is asking but I thought I could help others that stumble onto this question.

这里有一些方法,以风格<option>与沿<select>,如果你使用引导和/或jQuery的。我知道这不是原始海报的要求,但我想我可以帮助其他偶然发现这个问题的人。

You can still achieve the goal of styling each <option>separately, but may need to apply some style to the <select>as well. My favorite is the "Bootstrap Select" library mentioned below.

您仍然可以实现<option>分别为每个样式设置样式的目标,但也可能需要对它们应用一些样式<select>。我最喜欢的是下面提到的“Bootstrap Select”库。



Bootstrap Select Library (jquery)

Bootstrap 选择库 (jquery)

If you're already using bootstrap, you can try the Bootstrap Selectlibraryor the library below (since it has a bootstrap theme).

如果您已经在使用引导程序,则可以尝试引导程序选择或下面的库(因为它具有引导程序主题)。

Note that you are able to style the entire selectelement, or the optionelements separately.

请注意,您可以为整个select元素或option单独的元素设置样式。

Examples:

例子

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

Dependencies: requires jQueryv1.9.1+, Bootstrap, Bootstrap's dropdown.js component, and Bootstrap's CSS

依赖项:需要jQueryv1.9.1+、Bootstrap、Bootstrap 的 dropdown.js 组件和 Bootstrap 的 CSS

Compatibility: Unsure, but bootstrap says it "supports the latest, stable releases of all major browsers and platforms"

兼容性:不确定,但 bootstrap 说它“支持所有主要浏览器和平台的最新、稳定版本”

Demo: https://developer.snapappointments.com/bootstrap-select/examples/

演示https: //developer.snapappointments.com/bootstrap-select/examples/

.special {
  font-weight: bold !important;
  color: #fff !important;
  background: #bc0000 !important;
  text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-select.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-select.min.js"></script>

<select class="selectpicker">
  <option>Mustard</option>
  <option class="special">Ketchup</option>
  <option style="background: #5cb85c; color: #fff;">Relish</option>
</select>



Select2 (JS lib)

Select2(JS库)

There's a library you can use called Select2.

您可以使用一个名为Select2的库。

select2

选择2

Dependencies: Library is JS + CSS + HTML only (does not require JQuery).

依赖项:库仅是 JS + CSS + HTML(不需要 JQuery)。

Compatibility: IE 8+, Chrome 8+, Firefox 10+, Safari 3+, Opera 10.6+

兼容性:IE 8+、Chrome 8+、Firefox 10+、Safari 3+、Opera 10.6+

Demo: https://select2.org/getting-started/basic-usage

演示https: //select2.org/getting-started/basic-usage

There's also a bootstrap themeavailable.

还有一个引导程序主题可用。

No Bootstrap example:

没有 Bootstrap 示例:

$(function() {
  var $select = $('.select2');
  
  $select.select2({
    theme: 'paper'
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>

<select class="select2 form-control" placeholder="Country">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
</select>

Bootstrap example:

引导程序示例:

$(function() {
  var $select = $('.select2');
  
  $select.select2({
    theme: 'paper'
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/paper/bootstrap.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>

<select class="select2 form-control" placeholder="Country">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
</select>



MDBootstrap ($ & Bootstrap & JQuery)

MBootstrap ($ & Bootstrap & JQuery)

If you have extra money, you can use a premium library MDBootstrap. (This is an entire UI Kit, so it's not light)

如果您有多余的钱,可以使用高级库MBootstrap。(这是一个完整的 UI Kit,所以它不轻)

This allows you to style your select and option elements using the Material design.

这允许您使用Material design来设置您的选择和选项元素的样式。

enter image description here

在此处输入图片说明

There is a free version, but it won't allow you to use the pretty Material design!

有一个免费版本,但它不允许您使用漂亮的 Material 设计!

Dependencies: Bootstrap 4, JQuery,

依赖项Bootstrap 4、JQuery、

Compatibility: "supports the latest, stable releases of all major browsers and platforms."

兼容性“支持所有主要浏览器和平台的最新、稳定版本。”

Demo: https://mdbootstrap.com/docs/jquery/forms/select/#color

演示https: //mdbootstrap.com/docs/jquery/forms/select/#color

回答by HoldOffHunger

Seems like I can just set the CSS for the selectin Chrome directly. CSS and HTML code provided below :

好像我可以select直接在 Chrome 中设置 CSS 。下面提供了 CSS 和 HTML 代码:

.boldoption {
 font-weight: bold;
}
<select>
 <option>Some normal-font option</option>
 <option>Another normal-font option</option>
 <option class="boldoption">Some bold option</option>
</select>
enter image description here在此处输入图片说明

回答by AlexM

As already mentioned, the only way is to use a plugin that replaces <select>functionality.

如前所述,唯一的方法是使用替代<select>功能的插件。

A list of jQuery plugins: http://plugins.jquery.com/tag/select/

jQuery 插件列表:http: //plugins.jquery.com/tag/select/

Take a look at the example using Select2plugin: http://jsfiddle.net/swsLokfj/23/

看一下使用Select2插件的例子:http: //jsfiddle.net/swsLokfj/23/

回答by Bhetzie

Bootstrap allows you to use styling via data-content:

Bootstrap 允许您通过数据内容使用样式:

<select class="selectpicker">
  <option data-content="<span class='label label-success'>Relish</span>">Relish</option>
</select>

Example: https://silviomoreto.github.io/bootstrap-select/examples/

示例:https: //silviomoreto.github.io/bootstrap-select/examples/

回答by dy_

Some properties can be styled for<option>tag:

一些属性可以为<option>标签设置样式:

  • font-family
  • color
  • font-*
  • background-color
  • font-family
  • color
  • font-*
  • background-color

Also you can use custom font for individual <option>tag, for example any google font, Material Iconsor other icon fonts from icomoonor alike. (That may come handy for font selectors etc.)

您也可以为单个<option>标签使用自定义字体,例如任何谷歌字体材质图标或来自icomoon或类似的其他图标字体。(这对于字体选择器等可能会派上用场)

Considering that, you can create font-family stack and insert icons in <option>tags, eg.

考虑到这一点,您可以创建字体系列堆栈并在<option>标签中插入图标,例如。

    <select>
        <option style="font-family: 'Icons', 'Roboto', sans-serif;">a    ★★★</option>
        <option style="font-family: 'Icons', 'Roboto', sans-serif;">b    ★★★★</option>
    </select>

where is taken from Iconsand the rest is from Roboto.

取自哪里Icons,其余来自Roboto.

Note though that custom fonts do not work for mobile select.

请注意,自定义字体不适用于移动选择。

回答by Mr. Garrison

It's 2017 and it IS possible to target specific select options. In my project I have a table with a class="variations", and the select options are in the table cell td="value", and the select has an ID select#pa_color. The option element also has a class option="attached"(among other class tags). If a user is logged in as a wholesale customer, they can see all of the color options. But retail customers are not allowed to purchase 2 color options, so I've disabled them

现在是 2017 年,可以针对特定的选择选项。在我的项目中,我有一个带有class="variations"的表,选择选项位于表单元格td="value" 中,并且选择具有 ID select#pa_color。option 元素还有一个 class option="attached"(在其他类标签中)。如果用户以批发客户身份登录,他们可以看到所有颜色选项。但是零售客户不允许购买 2 种颜色选项,所以我禁用了它们

<option class="attached" disabled>color 1</option>
<option class="attached" disabled>color 2</option>

It took a little logic, but here is how I targeted the disabled select options.

这需要一点逻辑,但这里是我如何定位禁用的选择选项。

CSS

CSS

table.variations td.value select#pa_color option.attached:disabled {
display: none !important;
}

With that, my color options are only visible to wholesale customers.

这样,我的颜色选项仅对批发客户可见。