Bho*_*yar 2 html css css-selectors
HTML:
<div id="header">
<div id="one">
<ul class="menu">
<li>one text</li>
</ul>
</div>
<div id="two">
<ul class="menu">
<li>one text</li>
</ul>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这个CSS不起作用
#header ul.menu{
background-color: red;
text-align: left;
}
#two ul{ /*this line*/
background-color: blue;
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
这个css工作
#header ul.menu{
background-color: red;
text-align: left;
}
#two ul.menu{ /*this line*/
background-color: blue;
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
更新
根据css特异性的答案,比具体#header ul.menu更具体#two ul.我仔细检查了ul.menu比ul更具体.
ul.menu{...}
#two ul{...} /* works exactly, yes #two is more specific than ul.menu */
Run Code Online (Sandbox Code Playgroud)
好的,改变订单
订单1:
#header ul.menu{
background-color: red;
text-align: left;
}
#two ul.menu{ /* this selector works as per the specificity */
background-color: blue;
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
为什么#two ul.menu比具体更具体#header ul.menu?(演示不需要演示,因为顶级的第一个演示显示了这一点)
订单2:
#two ul.menu{
background-color: blue;
text-align: right;
}
#header ul.menu{ /* this selector works as per the specificity */
background-color: red;
text-align: left;
}
Run Code Online (Sandbox Code Playgroud)
为什么#header ul.menu比具体更具体#two ul.menu?演示
这是因为类选择器#header ul.menu使它更具体#two ul,即使它在结构方面#two"更接近" ul.特异性并不关心一个元素与另一个元素的"接近"程度.它甚至不计算组合器,所以即使你使用#two > ul它也不会有所作为.
如果您要选择相同的元素,则没有理由不平衡选择器的特异性,并将类选择器保留在两个规则中:
#header ul.menu{
background-color: red;
text-align: left;
}
#two ul.menu{
background-color: blue;
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
或者从两个规则中删除它:
#header ul{
background-color: red;
text-align: left;
}
#two ul{
background-color: blue;
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
根据您的需要.
在您的更新中,您只需切换两个同样具体的规则.后面的规则总是覆盖先前的规则.同样,这与元素结构无关.