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

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

最佳答案

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

The following list of selector types is by increasing specificity:

  1. Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
  2. Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
  3. ID selectors (e.g., #example).

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

jsFiddle example

有很多CSS specificity calculators在线可用,您可以看到 a:hover 具有 0011 的特异性,而 #feed a:hover 具有 0111.

关于除非我指定确切的选择器,否则不应用 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38257058/

相关文章:

javascript - 删除在图像 Canvas HTML5 上绘制的彩色线条

html - 样式禁用 <select multiple> 控件

CSS 过渡仅对元素淡入

javascript - 为数组的某些值设置样式

javascript - html 时钟的突然滚动条显示

HTML - 滚动条截断文本

javascript - 有哪些方法可以使图像具有模糊效果?

html - 图像在平板电脑和手机上扩大而不是缩小?

javascript - 如何在 D3.js 中将矩形居中?

css - 在我的 Android 上调试 JQuery Mobile