【问题标题】:How to change link color on hover and change it back (with per-link styling)?如何在悬停时更改链接颜色并将其更改回来(使用每个链接样式)?
【发布时间】:2021-09-20 17:13:46
【问题描述】:

我网站上的每个链接都有一个独特的颜色,它在每个 <a> 标记内的 style 参数中定义。我希望能够将页面上每个链接的背景颜色更改为浅绿色,并在悬停时将文本颜色更改为白色。但是,由于每个链接的颜色不同,文本颜色不会改变并被覆盖。我该如何解决这个问题?

这是我的代码:

a {
  color: black;
}

a:hover {
  background-color: aqua;
  color: white;
}
<a href=about style="color:cyan">About</a><br>
<a href=how style="color:magenta">How this site was made</a><br>
<a href=changelog style="color:goldenrod">Upcoming Changes & Changelog</a><br>

编辑:澄清一下,我希望链接保持原来的颜色,但我希望它们在悬停时变为白色,并在非悬停时变回。高亮颜色更改已经生效。

【问题讨论】:

  • 我也会在每个链接上添加一个小填充。 2px左右。
  • 我会先解决原来的问题,即使用内联样式而不是尝试添加更多问题
  • @RickardElimää 感谢您的提示,但这只是我的代码的一小部分。实际内容包含在 div 中,我使用的是外部样式表。所以它在我的实际网站上有填充。不过,我只发布了在这种情况下重要的内容。
  • @TemaniAfif 我还应该如何设置文本样式以便每个链接都可以是自己的颜色?我是 HTML 新手,所以我不知道该怎么做。
  • 使用类并使用选择器定位您的元素

标签: html css highlight


【解决方案1】:

您可以使用!important 属性来覆盖内联样式

a {
  color: black;
}

a:hover {
  background-color: aqua;
  color: white !important;
}
<a href=about style="color:cyan">About</a><br>
<a href=how style="color:magenta">How this site was made</a><br>
<a href=changelog style="color:goldenrod">Upcoming Changes & Changelog</a><br>

【讨论】:

    【解决方案2】:

    使用!important 属性覆盖所有其他声明:

    a {
      color: black;
    }
    
    a:hover {
      background-color: aqua;
      color: white !important;
    }
    <a href=about style="color:cyan">About</a><br>
    <a href=how style="color:magenta">How this site was made</a><br>
    <a href=changelog style="color:goldenrod">Upcoming Changes & Changelog</a><br>

    【讨论】:

      【解决方案3】:

      使用 CSS 变量而不是内联颜色,这样您就不必处理 !important 和特异性问题:

      a {
        color: var(--c,black);
      }
      
      a:hover {
        background-color: aqua;
        color: white;
      }
      <a href=about style="--c:cyan">About</a><br>
      <a href=how style="--c:magenta">How this site was made</a><br>
      <a href=changelog style="--c:goldenrod">Upcoming Changes & Changelog</a><br>

      【讨论】:

      • 谢谢!我会这样做,因为我意识到这是解决问题的更专业的方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多