html – 重置css中的伪类更改

在下面的代码片段中,我将第一个列表项设为红色,并隐藏了所有其他列表项.

然后,我尝试显示所有列表项,并通过定位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>

解决方法

增加最后一个选择器的 specificity以获得所需的结果.

下面是一个示例,其中所有选择器具有相同的特性(类伪类),最后一个将获胜:

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>

相关文章

HTML代码中要想改变字体颜色,常常需要使用CSS样式表。CSS是...
HTML代码如何让字体盖住图片呢?需要使用CSS的position属性及...
HTML代码字体设置 在HTML中,我们可以使用标签来设置网页中的...
在网页设计中,HTML代码的字体和字号选择是非常重要的一个环...
HTML(Hypertext Markup Language,超文本标记语言)是一种用...
外链是指在一个网页中添加一个指向其他网站的链接,用户可以...