CSS类优先级

25

我对CSS类的优先级有一个问题,今天遇到了一个问题。情况如下:

我有一个带有关联类的无序列表。 LI标签也定义了一些样式。我想在单击后更改LI的样式(通过添加的"selected"类),但是添加类的样式从未应用。这是正常行为还是代码应该起作用?

CSS:

.dynamicList
{
    list-style: none;
}

.dynamicList li
{
    display: block;
    width: 400px;
    height: 55px;
    padding: 10px 10px 10px 10px;
    border: 1px solid #000;
    background-color: #ff0000;
}

.selectedItem
{
    background-color: #0000ff;
}

HTML:

<ul class="dynamicList">
  <li>First Item</li>
  <li class="selectedItem">Second (Selected) Item</li>
</ul>

选中的列表项"selected"的背景颜色没有改变。即使不将样式应用于LI元素,而是创建另一个类并将其应用于所有列表项,情况也是如此。

<li class="listitem selectedItem">xxxx</li>
4个回答

26
这似乎是一个CSS特异性问题。尝试将您的.selectedItem规则集更改为:
.dynamicList li.selectedItem {
  background-color: #0000ff;
}

当然,我真是个白痴!非常感谢你的快速回答!干杯 斯图尔特 - Stuart

17
简短回答是,你的".selectedItem"样式没有被应用,因为之前的样式更具体,因此优先级更高。这里有一个不错的概述

Now, let’s make a general list of the internal priorities for CSS (3 has the highest priority):

element
.class
#id

This is the default priority order. In addition to this, specificity will also count, f.ex ul li will override li. W3C has made a decent table over how you should calculate internal weight:

LI            {...}  /* a=0 b=0 c=1 -> specificity =   1 */
UL LI         {...}  /* a=0 b=0 c=2 -> specificity =   2 */
UL OL LI      {...}  /* a=0 b=0 c=3 -> specificity =   3 */
LI.red        {...}  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red  {...}  /* a=0 b=1 c=3 -> specificity =  13 */
#list         {...}  /* a=1 b=0 c=0 -> specificity = 100 */

这里是W3C规范


7

selectedItem规则更改为:

.dynamicList li.selectedItem
{
    background-color: #0000ff;
}

2

在cletus的帖子中未提到的一个小补充。
根据W3C链接,最高优先级是在html元素/标签中使用的style属性。

例如,如果您有以下代码:

<a id= bar style="color: red">foo</a>

并且

<style>
#bar {
    color: blue;
}
</style>

颜色将为红色,因为内联 HTML 样式具有最高优先级,高于 #


今天我得知W3C被认为是代码信息的不良来源:http://www.w3fools.com - gersande
1
W3C 不是一个坏的资源,W3Schools 是。 - Touki
我感觉自己像个学生,所以我喜欢W3School,它提供了许多不同主题的信息和示例。W3C是官方标准和国际社区,因此从定义上来说一定很好。 - Timo

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