Search code examples
htmlcsshighlight

How to change link color on hover and change it back (with per-link styling)?


Each of the links on my website has a unique color, which is defined within the style argument within each <a> tag. I want to be able to change the background color of each link on the page to aqua and change the text color to white on hover. However, because of the separate color per link, the text color does not change and is overwritten. How can I get around this?

Here is my code:

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>

Edit: To clarify, I want the links to remain the color they are, but I want them to change to white on hover, and change back on non-hover. The highlight color change already works.


Solution

  • Use CSS variables instead of inline color so you don't have to deal with !important and specificity issues:

    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>