CSS更改列表项背景颜色与类 [英] CSS Change List Item Background Color with Class

查看:37
本文介绍了CSS更改列表项背景颜色与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改一个列表项的背景颜色,而其他列表项有另一种背景颜色.

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;
}
   

<ul class="nav">
 <li>Category 1</li>
 <li>Category 2</li>
 <li class="selected">Category 3</li>
 <li>Category 4</li>
</ul>

这会产生所有带有蓝色背景的列表项(来自nav"类),就好像没有selected"类一样.但是,当我从nav"类中取出背景颜色时,我会得到带有selected"类的列表项的红色背景.

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.

我想为页面上的其他项目(即其他列表项、div 等)使用选定"类.

I would like to use the "selected" class for other items on the page (i.e. other list items, divs, etc.).

我将如何解决这个问题?

How would I go about solving this?

提前谢谢你.

推荐答案

这是选择器特异性的问题.(选择器 .selectedul.nav li 具体less.)

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 .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

这样更简洁,打字更少,位数也更少.

That's a bit cleaner, less typing, and fewer bits.

这篇关于CSS更改列表项背景颜色与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆