为什么 CSS 中 a:hover 必须位于 a:link 和 a:visited 之后?

Che*_*Tan 2 html css pseudo-class

为什么w3schools说我们在CSS中编写锚点伪类时应该a:link先写然后a:visited再写a:hover最后a:active才是有效的?

来自:https://www.w3schools.com/css/tryit.asp?filename=trycss_link

伪类的顺序如何影响有效性?

Ada*_* K. 5

因为有一个优先顺序。

如果悬停在访问之前,则悬停将不会被应用,因为它将“永远”被访问的样式覆盖(如果它确实被访问过),这是在之后应用的。

:active (mouse down) 也是如此 - 如果它是在悬停之前定义的,那么悬停将始终覆盖 :active(mouse down)

说得通?


另一方面,这只是“约定俗成的规则” ——并不是强迫的。如果有人想要 :visited 更高的优先级,覆盖 :hover/:active - 你可以自由地这样做 -这只是非常规的


最后,不仅仅是顺序起着风格优先的作用。

定义更明确的元素具有更高的优先级。这些样式!important将比显式定义的样式具有更高的优先级。

使用 和 最后设置显式定义的样式!important将具有“最终”优先级。

询问“为什么要使用这些来覆盖样式?在 CSS 文件中正确排序样式不是更好吗? ” - 通过更明确的定义使用覆盖的原因和 !important 优先级覆盖在您使用时会很方便使用您尚未创建的大型 css/主题/引导程序,并且您必须快速覆盖/更改一些内容...这些肮脏的覆盖是一种快速/廉价(不是很漂亮)的解决方案。

.theBad:active {
  color: red;
}

.theBad:hover {
  color: green;
}

.theGood:hover {
  color: green;
}

.theGood:active {
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<a href="#" class="theGood">the Good</a> - this will turn red on mouse down
<br />
<a href="#" class="theBad">the Bad</a> - this poor little thing will not

<!--#ordermatters, The Ugly is lurking somewhere in the shadows-->
Run Code Online (Sandbox Code Playgroud)