重置CSS中的伪类更改

3
在下面的代码片段中,我将第一个列表项设置为红色,并隐藏了所有其他列表项。
然后,我尝试通过定位到li元素来显示所有列表项并使它们都变成黑色。
目前,使用最后一个li选择器没有任何视觉输出的变化。
所以,我想知道为什么最后一个li选择器对视觉输出没有影响?
谢谢。

li:not(:first-child) { /* Hide all li elements other than the first one */
  display: none;
}

li:first-child { /* Set list item 1 to be red */
  color: red;
}

/* Undo all changes above */
li { /* Make all li elements have this property ()*/
  display: block;
  color: black;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>


我希望列表中的所有三个项目都是黑色的,而不仅仅是第一个项目是红色的。 - Nick Parsons
2个回答

4

提高最后一个选择器的优先级以获得所需的结果。

以下是一个示例,其中所有选择器具有相同的优先级(类 + 伪类),并且最后一个选择器将获胜:

li:not(:first-child) { /* Hide all li elements other than the first one */
  display: none;
}

li:first-child { /* Set list item 1 to be red */
  color: red;
}

/* Undo all changes above */
li:nth-child(n) { /* Make all li elements have this property ()*/
  display: block;
  color: black;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>


谢谢,这很有道理。你知道为什么我需要选择所有的第n个子元素吗?选择li不已经包含了这个吗? - Nick Parsons
@Nick Parsons:如上所述,:nth-child()提供了伪类特定性以匹配前两个规则。您可以将其替换为任何其他保证匹配的伪类,例如:not(:root)。 - BoltClock
@NickParsons 是的,li 就足够了,而 nth-child 不会对选择器添加任何限制,它只会增加特异性。它对选择没有影响,只对特异性有影响。 - Temani Afif
1
@NickParsons,阅读我分享的链接,你会得到更多信息 ;) - Temani Afif

2

来自 https://developer.mozilla.org/zh-CN/docs/Web/CSS/:not

这个伪类可以增加规则的特异性。例如, #foo:not(#bar) 将会匹配与简单的 #foo 相同的元素,但是它具有更高的特异性。

您的第一个规则具有比最后一个规则更高的特异性,因此 display: none; 仍然生效,而 display: block; 被忽略。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接