选项组标签的样式选项

20

在下拉选择器中,是否可能仅对optgroup的标签进行样式设置?

<select>
    <optgroup label="Group Name">
        <option>My option</option>
    </optgroup>
</select>
4个回答

26

使用属性选择器

[label]
{
color: red;
}

编辑

<select>
<optgroup label="Cars">
<option>Honda</option>
<option>Merc</option>
</optgroup>
<optgroup label="Bikes">
<option>Kawasaki</option>
<option>Yamaha</option>
</optgroup>
</select>


optgroup[label="Cars"]
{
color: red;
}

optgroup[label="Bikes"]
{
color: blue;
}

option
{
color: black;
}

这只是一个例子。使用更具体的选择器。如你所说,它会影响整个组。为了解决这个问题,使用“option {color: black;}”。 - Jawad

13
我知道这个帖子有点旧了,但是以防万一像我一样遇到这个问题的人还会看到这个帖子…… 已经提到过当使用optgoup标签进行样式设置时,它会同时应用于整个组。这是正确的,但是如果你单独为option标签设置样式,则针对optgroup的样式仍将保持原样,而作为optgroup子元素的option标签的样式将覆盖没有设置option样式时继承的optgroup样式。
因此,为optgroup设置以下CSS样式将使文本呈现红色,背景呈现灰色。
optgroup {
    background-color: gray;
    color: red;
}

如果不做其他操作,您的整个列表将是灰色背景上的红色文本。然而,设置以下选项样式也会使opt组标签在灰色背景上保持红色样式,但是组下的选项将变成黑色文本白色背景。

option {
    background-color: white;
    color: black;
}

5
使用[label] 属性选择器,正如大家建议的那样,往往没有意义。你不能将样式应用于HTML属性。它只是一个修改器,用于过滤optgroup元素。如果所有的optgroup都有一个label,那么你会选择它们所有,如果有些没有label,那么它们就会退出样式:

optgroup[label]{
  color: red;
}
<select size="8">
  <optgroup label="Cars">
    <option>Honda</option>
    <option>Merc</option>
  </optgroup>
  <optgroup>
    <option>Not label</option>
    <option>Not label either</option>
  </optgroup>
  <optgroup label="Bikes">
    <option>Kawasaki</option>
    <option>Yamaha</option>
  </optgroup>
</select>

<select>标签和<input type="file">等其他复杂的表单控件存在相同的问题。最初的规范认为应该由浏览器来决定如何显示它(事实上,通常是由底层库提供的内置图形用户界面控件),并没有提供全面的样式化方式。请看一下在W3C HTML 4.01规范中找到的这个截图:

optgroup at HTML4

回到我们的问题,有两个要考虑的事实:
  • <optgroup>是一个包含子元素<option> 的块
  • 标签本身并没有一个节点
这段代码可以使其更加清晰:

optgroup{
  margin: 1em;
  border: 1px solid green;
}
optgroup option{
  margin: 1em;
  border: 1px solid orange;
}
<select size="13">
  <optgroup label="Cars">
    <option>Honda</option>
    <option>Merc</option>
  </optgroup>
  <optgroup label="Bikes">
    <option>Kawasaki</option>
    <option>Yamaha</option>
  </optgroup>
</select>

你所能做的就是对 <optgroup> 应用样式(因为你无法将标签与其他项目区分开来),然后根据需要覆盖子选项。


2
某些 CSS 属性(例如 border)只有在 <select> 具有大于 1 的 size 属性时才呈现。我认为这是因为当 size > 1 时,选择的内容会永久呈现在页面上,但是当 size = 1(或未指定 - select 的正常情况),只有在单击选择时才会呈现内容。在这种情况下,<option><optgroup> 都会忽略一些 CSS 属性,包括边框和外边距。(已在 Chrome Windows 上测试过。在移动设备上将完全不同)。 - Mark Chitty

4
<style type="text/css">
    optgroup[label] {
        background: #FFFFFF;
    }
</style>

或者

<style type="text/css">
    optgroup[label="Group Name"] {
        background: #FFFFFF;
    }
</style>

如果您想使其标签特定,请按如下方式操作。

3
将<option>的样式重置为"option {color: black;}"。这样会覆盖在optgroup上设置的样式。 - Jawad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接