CSS更改列表项背景色级 [英] CSS Change List Item Background Color with Class
问题描述
我试图改变一个列表项的背景颜色,同时还有其他列表项另一个背景颜色。
I am trying to change the background color of one list item while there is another background color for other list items.
这是我有:
<style type="text/css">
ul.nav li
{
display:inline;
padding:1em;
margin:1em;
background-color:blue;
}
.selected
{
background-color:red;
}
</style>
<ul class="nav">
<li>Category 1</li>
<li>Category 2</li>
<li class="selected">Category 3</li>
<li>Category 4</li>
</ul>
这是什么产生是与蓝色背景(从导航类)的所有列表项,因为如果没有选择类。然而,当我拿出从导航类的背景颜色,我得到的选择级列表项目的红色背景。
What this produces is all list items with a blue background (from the "nav" class), as if there were no "selected" class. However, when I take out the background color from the "nav" class, I get the red background for the list item with the "selected" class.
我想用其他项目的选择类网页上(即其他列表项,申报单等)。
I would like to use the "selected" class for other items on the page (i.e. other list items, divs, etc.).
我将如何去解决呢?
感谢您提前。
推荐答案
这是选择特异性的问题。 (选择器 .selected
是少的具体比 ul.nav丽
)
This is an issue of selector specificity. (The selector .selected
is less specific than ul.nav li
.)
要修复,在原有的使用尽可能多的特异性压倒一切的规则为:
To fix, use as much specificity in the overriding rule as in the original:
ul.nav li {
background-color:blue;
}
ul.nav li.selected {
background-color:red;
}
您也可以考虑坭兴在 UL
,除非会有其他 .nav
秒。所以:
You might also consider nixing the ul
, unless there will be other .nav
s. So:
.nav li {
background-color:blue;
}
.nav li.selected {
background-color:red;
}
这是一个有点清洁,少打字,和更少的位。
That's a bit cleaner, less typing, and fewer bits.
这篇关于CSS更改列表项背景色级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!