CSS 类优先级
今天遇到问题后,对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>
I have a question about the priority of CSS classes after encountering a problem today. The situation is as follows:
I have an unordered list which has a class associated with it. The LI
tags have some styles defined too. I want to change the styling of the LI
s after a click (via an added "selected"
class), but the added class's styles are never applied. Is this normal behavior or should this code work?
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>
The background color of the "selected"
list item isn't changed. This is also the case if I don't apply the style to the LI
element, but create another class and apply that to all the list items so it reads..
<li class="listitem selectedItem">xxxx</li>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这听起来像是 CSS 特异性问题。 尝试将您的
.selectedItem
规则集更改为:This sounds like a CSS specificity problem. Try changing your
.selectedItem
ruleset to:简而言之,您的 .selectedItem 样式没有被应用,因为以前的样式更具体,因此具有更高的优先级。 这是一个不错的概要:
这是W3C 规范。
The short answer is that your .selectedItem style isn't getting applied because the previous style is more specific and thus has a higher priority. Here is a decent rundown:
And here is the W3C specification.
将
selectedItem
规则更改为:Change the
selectedItem
rule to:cletus 的帖子中没有提到的一个小补充。
根据
W3C
链接,最高优先级是html元素/标签中使用的style
属性。例如,如果你有
and
颜色将为
red
,因为内联html样式具有最高优先级,高于#
。A small addition that was not mentioned by cletus' post.
According to the
W3C
link, the highest priority is thestyle
attribute used in the html element/tag.E.g. if you have
and
The color will be
red
because the inline html style has the highest priority, higher than#
.