除非我指定精确的选择器,否则不会应用CSS样式

时间:2016-07-07 23:58:16

标签: css

我认为这种情况很奇怪,在哪里

a:hover {
    color: #FD5454;
}

不起作用,但

#feed h3 a:hover {
    color: #FD5454;
}

一样。自从我广泛使用CSS以来已经有一段时间了,所以我不知道为什么。有人可以向我解释一下吗?这肯定是一个愚蠢的问题,但我自己也无法弄明白。提前谢谢!

编辑: 以下是它正在影响的代码:

<div id="feed">
    <h2>Follow us on 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;
}

/* This is working */
#feed h3 a:hover {
    color: #FD5454;
}

/* This is not */
a:hover {
    color: #FD5454;
}

1 个答案:

答案 0 :(得分:5)

这是java-object-copy-using-beanutils的情况。在这里,您的a:hover选择器不够具体,无法覆盖#feed h3 a规则。正如MDN所说:

  

以下选择器类型列表是通过提高特异性来实现的:

     
      
  1. 类型选择器(例如,h1)和伪元素(例如:之前)。
  2.   
  3. 类选择器(例如.example),属性选择器(例如,[type =“radio”])和伪类(例如:hover)。
  4.   
  5. ID选择器(例如,#example)。
  6.   

正如您所发现的那样,通过在悬停选择器(#feed)前面添加#feed a:hover会增加特异性以覆盖其他选择器。

<强> CSS specificity

网上有很多jsFiddle example,您可以看到a:hover的特异性为0011,而#feed a:hover的{​​{1}}为0111