【问题标题】:parent class properties not getting applied to child anchor tag element父类属性未应用于子锚标记元素
【发布时间】:2021-05-18 02:40:30
【问题描述】:

我正在创建一个具有 top-navbar 类的导航栏。我在div 中包含了一些锚标记。当我在类上使用 CSS 属性 color: black 时,锚文本仍然是蓝色(原始颜色)。相反,当我在锚标记本身上使用属性 color: black 时,它可以工作吗?为什么对class属性不起作用,是不是被div后面的所有元素都继承了 class= nav-bar-items 标记如下:

<div class="top-navbar">
  <img class="logo-img" src="https://freesvg.org/download/47093">
  <div class="nav-bar-items">
    <a href="https://xyz.info/about">about</a>
    <a href="https://xyz.info/notes">notes</a>
    <a href="htts://xyz.info/contact">contact</a>
  </div>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您已经知道如何将锚文本变黑的解决方案有很多。 但你的问题是为什么不继承?这是我对提供的 css 对您不起作用的原因的解释。

    CSS 特异性

    计算特异性的规则由{style, ids, [classes, attributes and pseudo-classes], [elements and pseudo-elements] }定义

    如果我们计算锚标签上选择器的特异性,我们就会得到答案。

    a:-webkit-any-link(用户代理)-> 0011(1 用于伪类,1 对于元素)

    .top-navbar -> 0010

    很明显,这里的用户代理样式获胜并接管,所以颜色仍然是蓝色,请查看下面的快照。

    参考以了解更多信息 -

    https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/

    https://specificity.keegan.st/

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

    【讨论】:

      【解决方案2】:

      老实说,我不知道为什么,而且我很确定它已经在 SO 上得到了回答,但是当你可以定位你的链接时,为什么还要费心呢?只是一些例子,还有更多的方法:

      .nav-bar-items a {
          color:red;
        }
      
      .nav-bar-items > *{
          color:red;
        }
      

      了解选择器: CSS_Selectors

      【讨论】:

        【解决方案3】:

        a 标签正在获取浏览器默认样式,需要更具体的内容来覆盖它:

        .nav-bar-items a {
          color: black;
        }
        

        【讨论】:

          【解决方案4】:

          &lt;a&gt; 标签加载了默认样式属性。有不同的自定义方法。

          1. By using inheritance
          
                  .nav-bar-items > a {
            color: inherit;
            text-decoration: inherit;
          };
          
          
           2. override
          
                  .nav-bar-items a {
                  color:color-name;
                };
          
           3. This one is only, if your parent class has a single child <a> tag then you can use it. 
          
                  a:only-child {
                  color: color-name;
                };
          

          【讨论】:

            猜你喜欢
            • 2020-09-30
            • 2022-01-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-29
            相关资源
            最近更新 更多