如何添加:使用CSS2选择器将鼠标悬停在元素的第n个子元素上?

时间:2013-09-28 07:36:23

标签: css css-selectors

我试图在悬停时给每个菜单li一个独特的背景颜色,我想用css2来做。

<ul>
    <li>
    <li>
    <li>
    <li>
</ul>

我能够使用以下内容在第一个元素上添加背景:

nav ul > li:hover:first-child a { background-color:red !important; }

当我在2ndelement上添加不同的背景时,只有当我将光标放在第一个元素上时,才会出现下一个元素的悬停效果。

到目前为止,这是我的代码:

nav ul > li:hover:first-child a { background-color:red !important; }
nav ul > li:hover:first-child + li a { background-color:blue !important; }

使用CSS2有没有正确的方法?

我试图通过以下链接深入了解这个Boltclock的答案。

How do I get the nth child of an element using CSS2 selectors?

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:5)

第n个子元素由+链中的最后一个元素表示(紧跟在它之后的组合子之前,如果有的话),所以你要将:hover选择器附加到该元素,如下所示: / p>

nav ul > li:hover:first-child a { background-color:red !important; }
nav ul > li:first-child + li:hover a { background-color:blue !important; }

如果您希望为第一个孩子更清楚,您可以重新排序伪类,将:hover放在最后(即:first-child之后):

nav ul > li:first-child:hover a { background-color:red !important; }
nav ul > li:first-child + li:hover a { background-color:blue !important; }

最后,正如其他人提到的那样,除非您有特定的理由使用它们,否则应删除!important

答案 1 :(得分:2)

@BoltClock描述的方式是唯一的方法在CSS2 (如你所要求的)没有定义类(我个人会为每个列表项定义类作为你的解决方案,因为它更容易维护并且从现在开始几个月更容易记住它是如何工作的)。如果你可以使用CSS3,那么nth-child可能就是你想要的。

您的示例代码应该是这样的:

nav ul > li:hover:first-child a { background-color:red; }
nav ul > li:first-child + li:hover a { background-color:blue; }
nav ul > li:first-child + li + li:hover a { background-color:green; }
nav ul > li:first-child + li + li + li:hover a { background-color:yellow; }

答案 2 :(得分:1)

<ul>
  <li><a href="#">red</a></li>
  <li><a href="#">blue</a></li>
  <li><a href="#">green</a></li>
  <li><a href="#">yellow</a></li>
  <li><a href="#">magenta</a></li>
</ul>

li:first-child:hover a { background-color: red; }
li:nth-child(5):hover a { background-color: magenta; }

答案 3 :(得分:0)

在你的html中没有<a>个标签,但css规则正在尝试设置不存在的链接。试一试:

<ul>
  <li><a href="#">test 1</a></li>
  <li><a href="#">test 2</a></li>
  <li><a href="#">test 3</a></li>
  <li><a href="#">test 4</a></li>
  <li><a href="#">test 5</a></li>
</ul>

li:first-child:hover a { background-color: red; }
li:nth-child(2):hover a { background-color: blue; }

选中DEMO

另请注意,除非您需要覆盖其他样式,否则不需要使用!important,这可能会有问题,但有时会有用。