我试图让 CSS 优先级正确,但出于某种原因,此代码无法正确使用 #hs 中定义的 a:hover 样式。 #hs li.druid a:link
似乎覆盖了 #hs li a:hover
中定义的背景颜色,即使我只是指定 a:link 而不是 a :徘徊。它确实继承了其他东西,比如颜色。将代码放在哪里并不重要,我已经尝试将其切换,但结果相同。
HTML:
<div id="nav">
<ul id="hs">
<li class="druid">
<a href="druid">Druid</a>
</li>
</ul>
<div>
CSS:
#hs {
list-style-type: none;
padding: 0;
overflow: hidden;
}
#hs li a:link, #hs li a:visited {
display: block;
width: 150px;
font-weight: bold;
color: #FFFFFF;
padding: 10px 0px;
margin: 25px auto;
border-radius: 4px 4px 4px 4px;
text-transform: uppercase;
}
#hs li a:hover, #hs li a:active {
color: #00AA00;
background-color: orange;
text-decoration: none;
}
#hs li.druid a:link {
background-color: #855C33;
}
最佳答案
这是由于CSS specificity .
每个选择器的特殊性:
#hs li.druid a:link
- 122#hs li a:hover
- 112
您可以降低选择器 #hs li.druid a:link
的特异性。没有 id
,特异性从 122 降低到 22。
li.druid a:link {
background-color: #855C33;
}
更安全的方法是通过添加 id 选择器 #nav
来增加选择器 #hs li a:hover
的特异性。这样做时,您为每个选择器添加了 100 个点,从而允许它覆盖其他选择器。
#nav #hs li a:hover,
#nav #hs li a:active {
color: #00AA00;
background-color: orange;
text-decoration: none;
}
这是一个相对有用的链接 calculating specificity给定一个选择器。
关于html - CSS 优先链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28595484/