【问题标题】:CSS style not applied unless I specify the exact selector除非我指定确切的选择器,否则不会应用 CSS 样式
【发布时间】:2016-11-10 10:56:44
【问题描述】:

我有这种情况,我觉得很奇怪,在哪里

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;
}

【问题讨论】:

  • 您是否有其他优先于 a:hover 的 CSS 规则?
  • 没有。我还有一些使用 :hover 选择器的其他规则,但这些规则都会影响其他元素。
  • 你能在你的问题中发布minimal reproducible example吗?
  • @j08691 当然,我的错。我以为这只是一个简单而愚蠢的问题。 :)

标签: css


【解决方案1】:

这是CSS specificity 的情况。在这里,您的 a:hover 选择器不够具体,无法覆盖 #feed h3 a 规则。正如 MDN 所述:

以下选择器类型列表是通过增加特异性:

  1. 类型选择器(例如 h1)和伪元素(例如 :before)。
  2. 类选择器(例如 .example)、属性选择器(例如 [type="radio"])和伪类(例如 :hover)。
  3. ID 选择器(例如,#example)。

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

jsFiddle example

网上有很多CSS specificity calculators,你可以看到a:hover的特异性是0011,而#feed a:hover的特异性是0111

【讨论】:

  • 我的回答类型 :)
  • 感谢您在阅读 cmets 中的文章后输入我对该问题的怀疑。这让我明白了,谢谢!只要它不会变得不可维护,我就会使用特定的选择器。否则,在样式后添加 !important 即可。 ;)
猜你喜欢
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 2022-12-23
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多