html - 设置样式时颜色不会更改为特定类元素

标签 html css

这是我正在使用的 html 代码.......

<ul id="top_options">
<li>Discussions</li> 
<li>Tags</li> 
<li>Users</li>
<li class="selected_top_option">Unaddressed</li> 
<li>New Discussion</li> </ul>

这是我在上面的代码中使用的 CSS 部分...

#top_options
{
    display:inline;
    float:left;
}
#top_options li
{
    list-style:none;
    display:inline;
    margin-right:20px;
    background-color:#ADADAD;
    color:#FFF;
    font-size:16px;
    font-weight:bold;
    line-height:50px;
    padding-left:8px;
    padding-right:8px;
    font-family:Arial, Helvetica, sans-serif;
}
#top_options li:hover
{
    background-color:#FF8000;
    cursor:pointer;
}
.selected_top_option
{
    background-color:#F00;
    border:dotted;
}

问题是“未寻址”列表项应该以#F00 背景色显示,但它以#ADADAD 背景色显示,但它正在指定边框。我在这里缺少的重点是什么?

最佳答案

是因为specificity - 当您以两种不同的方式为同一元素定义相同的 CSS 属性时,将应用更具体的选择方法中的 CSS 属性。

#top_options li.selected_top_option 更具体,因此应用了 background-color 的定义。以这种方式思考 - 只能有一个具有 id 的东西,所以这是非常具体的,但是可以有很多东西具有 class,所以它不太具体.因此,id 胜出。

基于linked HTML Dog article (这不是确切特异性的计算方式,因为它忽略了例如 !important,但它是一种非常快速和简单的计算方法),特异性是:

.selected_top_option = 10 (1 class selector)
#top_options li = 101 (1 id selector + 1 element selector)

所以在这种情况下,101 更高(即更具体),并且只要这两者之间存在冲突,就会胜出。

另一篇关于特异性的好文章是 this Smashing Magazine article Google 上还有更多内容。

解决方案是使 .selected_top_option 更具体。我建议:

#top_options li.selected_top_option { /* your css here */ } 
.selected_top_option { background-color: #F00 !important; /* rest of css */ }

但是,在大多数情况下,我建议不要使用 !important,因为它会使以后覆盖变得更加复杂。

关于html - 设置样式时颜色不会更改为特定类元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5906564/

相关文章:

css - 模拟背景大小 : cover with center position on HTML5 <video>

javascript - 当我尝试使用 Javascript API 连接到 Dropbox 时按钮不呈现

右上角带有数据和状态的 HTML Div

html - 讨厌的 lil' <small> 元素不能与文本对齐一起工作,需要被阻止

html - 流体布局中不需要的水平滚动条

html - 为什么文字会褪色但图像不会褪色?

javascript - 更改html中的背景图片

javascript - Chrome 扩展覆盖

web-applications - WebSockets……它们不安全吗?

html - Bootstrap 3 不在手机和平​​板电脑上将元素居中