【问题标题】:Why h2 and h4 tags does not change coloк in hover state?为什么 h2 和 h4 标签在悬停状态下不会改变颜色?
【发布时间】:2019-01-16 22:09:13
【问题描述】:

我试图更改两个链接的文本颜色,同时将它们悬停在它们上方,但颜色没有改变?是什么原因?

h2 {
color: green;
}

h4 {
color: pink;
}

a:hover {
color: lightblue;
}

a {
text-decoration: none;
color: black;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href="#">
    <h2>This is a header</h2>
    <h4>This is another header</h4>
</a>

【问题讨论】:

  • 请在这个问题中添加一个可重现的例子。谢谢
  • 您的选择器需要更具体a:hover h2, a:hover h4 { ... }
  • @Turnip — 特异性不相关。定位正确的元素是。
  • 离题了,但我想知道 r 怎么会变成 к 作为拼写错误。我能理解它是否变成了р或什么的。

标签: html css hover


【解决方案1】:

元素是元素的任何颜色。

默认标题的颜色是inherit,因此它采用其父元素的颜色。

div {
  color: blue;
}
<div>
  The div is blue
  <h1>The h1 is blue</h1>
</div>

<h1>The h1 is black</h1>

但如果你明确设置它,那么它就是你设置的任何颜色......

div {
  color: blue;
}

h1 {
  color: pink
}
<div>
  The div is blue
  <h1>The h1 is pink</h1>
</div>

<h1>The h1 is pink</h1>

您将a 设置为lightblue,但由于标题不是color: inherit,因此它们不会继承它。 :hover 无关紧要。

编写一个以标题为目标的选择器(例如a:hover h2, a:hover h4 { … }

【讨论】:

    【解决方案2】:

    你可以像下面那样做,用*选择锚点内的所有元素,见下文。

    h2 {
    color: green;
    }
    
    h4 {
    color: pink;
    }
    
    a:hover * {
    color: lightblue;
    }
    
    a {
    text-decoration: none;
    color: black;
    }
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <a href="#">
        <h2>This is a header</h2>
        <h4>This is another header</h4>
    </a>

    【讨论】:

      【解决方案3】:
      a:hover h2,
      a:hover h4 {
          color: lightblue;
      }
      

      试试这个!

      【讨论】:

        【解决方案4】:

        看起来某些内联样式(强)可能超过 CSS 悬停。下面的示例将强样式放在带有 span 的 CSS 文档中。我还在悬停指令中包含了其他两个元素。

        HTML &lt;a href="#"&gt; &lt;p&gt;This is a paragraph&lt;/p&gt;enter code here &lt;span&gt;This is strong&lt;/span&gt; &lt;/a&gt; CSS p {color: green;}

        `span {color: pink;`
        `font-weight: bold}`
        
        `a:hover, p:hover, span:hover  {color: lightblue;}`
        
        `a {text-decoration: none; color: black;}`
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-30
          • 2015-07-02
          • 1970-01-01
          • 2018-05-30
          • 2013-06-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多