不应用CSS样式,除非我指定了精确的选择器 [英] CSS style not applied unless I specify the exact selector
问题描述
我有这种情况我认为很奇怪,其中
a:hover {
color: FD5454;
}
无效,但
#feed h3 a:hover {
color:#FD5454;
}
它已经有一段时间,因为我使用CSS广泛,所以我不知道为什么。有人可以解释这个给我吗?这肯定是一个愚蠢的问题,但我只是不能自己弄清楚。提前感谢!
编辑:
以下是影响此刻的代码:
< div id =feed>
< h2>在Instagram上关注我们< / h2>
< h3>< a href =http://www.instagram.com/johndoe> @ johndoe< / a>< / h3>
< / div>
以下是完整的样式规则:
a:link {
text-decoration:none;
color:white;
}
#feed {
text-align:center;
background:url(../ img / Feed_bg.jpg)center no-repeat;
height:100vh;
}
#feed h2 {
color:#789199;
padding-top:5vh;
}
#feed h3 a {
text-decoration:none;
font-family:Lato Light;
color:white;
}
/ *这是工作* /
#feed h3 a:hover {
color:#FD5454;
}
/ *这不是* /
a:hover {
color:#FD5454;
}
a href =https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity> CSS特性。这里, a:hover
选择器不够具体,不能覆盖 #feed h3 a
规则。作为MDN的注释:
下面的选择器类型列表是通过增加特异性:
<
类选择器(例如,.example),属性选择器(例如,例如[type =radio])和伪类(例如:hover)。
ID选择器(例如,#example)。
正如您所发现的,在悬停选择器前添加 #feed
( #feed a:hover
)增加了覆盖其他选择器的特异性。
有很多 CSS特异性计算器,您可以看到 a:hover
特异性 0011
,而 #feed a:hover
有 0111
。
I've got this situation I think is weird, where
a:hover {
color: #FD5454;
}
doesn't work, but
#feed h3 a:hover {
color: #FD5454;
}
does. It has been some time since I used CSS extensively, so I have no idea why. Could someone please explain this to me? It surely must be a stupid question, but I just couldn't figure it out myself. Thank you in advance!
EDIT: Here's the code it is affecting at the moment:
<div id="feed">
<h2>Follow us on instagram</h2>
<h3><a href="http://www.instagram.com/johndoe">@johndoe</a></h3>
</div>
And here are the complete style rules:
a:link {
text-decoration: none;
color: white;
}
#feed {
text-align: center;
background: url("../img/Feed_bg.jpg") center no-repeat;
height: 100vh;
}
#feed h2 {
color: #789199;
padding-top: 5vh;
}
#feed h3 a {
text-decoration: none;
font-family: "Lato Light";
color: white;
}
/* This is working */
#feed h3 a:hover {
color: #FD5454;
}
/* This is not */
a:hover {
color: #FD5454;
}
This is a case of CSS specificity. Here, your a:hover
selector isn't specific enough to override the #feed h3 a
rule. As MDN notes:
The following list of selector types is by increasing specificity:
- Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
- Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
- ID selectors (e.g., #example).
And as you discovered, by adding #feed
in front of your hover selector (#feed a:hover
) increases the specificity to override the other selector.
There are many CSS specificity calculators available online and you can see that a:hover
has a specificity of 0011
, while #feed a:hover
has 0111
.
这篇关于不应用CSS样式,除非我指定了精确的选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!