这是我正在使用的 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/