【问题标题】:understanding css specificity (a:active pseudo class)理解 css 的特殊性(a:active 伪类)
【发布时间】:2015-11-10 20:20:59
【问题描述】:

我的导航栏中有一组链接到其他页面的无序列表,我尝试设置我的 css 以便所有 ul 锚点具有相同的 :active 颜色。

在我的 css 文档上非常高,我做了以下操作:

/* will be overridden by more specific selectors as needed */
ul a:active{
    color: black;
}

这不起作用。没有什么可以覆盖它并强制活动状态保持相同的颜色。

我试图通过添加另一个选择器使其更具体,见下文:

.nav ul a:active{
    color: black;
}

它有效,但我不明白为什么会这样,我没有在其他任何地方为 a:active 分配值,所以第一个选择器应该可以解决问题。

我稍后在样式表中为锚点的正常状态添加了一些规则,见下文:

.nav ul a {
    display: block;
    padding: 20px;

    /*padding-right: 0 !important; wtf is this */
    /* important overrides media queries */
    font-size: 13px;
    text-align: center;
    color: #aaa;
    text-decoration: none;
    background-color: #f5f5f5;
}

我不认为这会覆盖我的第一个选择器...

【问题讨论】:

    标签: css selector pseudo-class css-specificity


    【解决方案1】:

    这是因为类和伪类在特异性上具有更大的权重。根据您的情况,从最具体到最不具体的顺序:

    • .nav ul a:active:2个类(包括1个伪类)
    • .nav ul a:1 个类 + 2 个元素
    • ul a:active:还有 1 个(伪)类 + 2 个元素,但在您的样式表中较早,因此它的特异性较低

    希望这可以解释为什么添加 .nav 确实会有所作为。

    【讨论】:

      【解决方案2】:

      根据W3C Selectors Level 3中的规范:

      • 统计选择器中 ID 选择器的数量 (= a)
      • 统计选择器中类选择器、属性选择器和伪类的数量 (= b)
      • 统计选择器中类型选择器和伪元素的数量 (= c)
      • 忽略通用选择器

      示例:

      *               /* a=0 b=0 c=0 -> specificity =   0 */
      LI              /* a=0 b=0 c=1 -> specificity =   1 */
      UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
      UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
      H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
      UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
      LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
      #x34y           /* a=1 b=0 c=0 -> specificity = 100 */
      #s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
      

      So when selectors have an equal specificity, the last rule is the one that counts, which is what's happening in your case.

      选择器细分:

      我们来算一算吧:

      • 第一个选择器组:两个类型选择器 (c) ul & a 和一个伪类 (b) :active
      • 第二个选择器组:一个类选择器 (b) .nav 和两个类型选择器 (c) ul & a

      最终结果是相同的特异性:

      ul a:active     /* a=0 b=1 c=2 -> specificity =  12 */
      .nav ul a       /* a=0 b=1 c=2 -> specificity =  12 */
      

      有用的资源:

      【讨论】:

        【解决方案3】:

        我不知道您网站的具体样式如何,但我可以给您一个一般提示:

        如果您使用的是 Google Chrome,您可以使用 https://developer.chrome.com/devtools 然后检查元素以查看该元素从哪个选择器(以及哪个样式表)获取其特定属性。

        您也可以使用 Firefox 执行此操作:https://developer.mozilla.org/en-US/docs/Tools 或 Internet Explorer https://msdn.microsoft.com/en-us/library/gg589500%28v=vs.85%29.aspx

        编辑:

        还找到了一个不错的链接,您可以在其中阅读有关特异性的更多信息,因为您的目标是理解它:

        https://css-tricks.com/specifics-on-css-specificity/

        【讨论】:

        • 正是我所做的。这就是我知道应用了哪个选择器的方式。
        猜你喜欢
        • 1970-01-01
        • 2014-07-11
        • 1970-01-01
        • 2012-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-09
        • 2011-05-08
        相关资源
        最近更新 更多