Reset pseudo class changes in css

一笑奈何 提交于 2021-02-16 19:37:06

问题


In the snippet below I have made the first list item red, and hidden all the other list items.

I am then trying to display all the list items and make them all black by targeting the li elements.

Currently, no changes using the last li selector are being made.

So, I'm wondering why the last li selector is having no effect on the visual output?

Thanks

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>

回答1:


Increase the specificity of the last selector in order to obtain the needed result.

Here is an example where all the selectors have the same specificity (class + pseudo-class) and the last one will win:

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>



回答2:


From https://developer.mozilla.org/en-US/docs/Web/CSS/:not

This pseudo-class can increase the specificity of a rule. For example, #foo:not(#bar) will match the same element as the simpler #foo, but has a higher specificity.

Your first rule has more specificity than the last rule, so the display: none; stays in effect while display: block; is ignored.



来源:https://stackoverflow.com/questions/51686079/reset-pseudo-class-changes-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!