【问题标题】:Pseudo Class 'nth-child()' not working with ':hover" [duplicate]伪类“nth-child()”不适用于“:悬停”[重复]
【发布时间】:2020-12-24 20:19:23
【问题描述】:

我正在尝试将伪类:nth-child():hover 一起使用,但它似乎对我不起作用。我试图在悬停时将一个元素的颜色更改为绿色,但它会突出显示所有元素。我也试过没有悬停,颜色都没有变化。

ul {
    background-color: white;
    text-decoration: none;
    padding: 0;
    margin: 0 auto;
}
ul li {
    margin: 0 2em;
    display: inline-block;
    padding: 0;
    list-style: none;
}
ul li a {
    text-decoration: none;
    color: black;
}
a:nth-child(2){
color: green;
}
<ul>
      <li><a href="#">Easy</a></li>
      <li><a href="#">Medium</a></li>
      <li><a href="#">Hard</a></li>
      <li><a href="#">Insane</a></li>
</ul>

【问题讨论】:

  • 您所有的链接都是第一个孩子。你需要在'li'上使用第n个孩子

标签: html css


【解决方案1】:

那是因为 a 不是第二个孩子 - 它是它的父母 li 的唯一孩子。您正在寻找的是第二个 li 元素的 a 子元素。你可以这样得到:

li:nth-child(2) a{ color: green; }

然后对于悬停,其中任何一个都可以与您问题中的代码一起使用。这取决于您希望悬停的目标:

// When the <a> in the second li is hovered, change it's colour
li:nth-child(2) a:hover{ color: green; }

/* OR */ 

/* When the second li is hovered, change the colour of the <a> it contains */
li:nth-child(2):hover a{ color: green; }

工作示例(使用不同的颜色来显示它的工作原理):

ul {
    background-color: white;
    text-decoration: none;
    padding: 0;
    margin: 0 auto;
}
ul li {
    margin: 0 2em;
    display: inline-block;
    padding: 0;
    list-style: none;
}
ul li a {
    text-decoration: none;
    color: black;
}

/* change colour of 2nd link */
li:nth-child(2) a{
    color: blue;
}

/* change colour of 2nd link on hover */
li:nth-child(2):hover a{
    color: green;
}

/* change colour of 3rd link on hover */
li:nth-child(3) a:hover{
    color: red;
}
<ul>
      <li><a href="#">Easy</a></li>
      <li><a href="#">Medium</a></li>
      <li><a href="#">Hard</a></li>
      <li><a href="#">Insane</a></li>
</ul>

参考Mozilla MDN Docs for nth-child

【讨论】:

  • 我想知道这行代码li:nth-child(2):hover a{color: green;} 为什么必须有一个选择器才能工作?第n个孩子不是已经选择了吗?
  • @Tony li.nth-child(2) 将选择第二个li,但是您想更改lia 元素的链接 颜色。所以当第二个li 悬停在上面时,这条线会改变它所包含的a 的颜色。
【解决方案2】:

我希望这段代码可以帮助你。并使用此链接了解有关伪类和元素的更多信息。Click here to learn about CSS Pseudo-classes

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 2014-08-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    相关资源
    最近更新 更多