skip to Main Content

How can I create a two-colored link that switches the colors when the mouse hovers over the text?

The result should behave like this:

link that switches colors upon mouse hover

Based on https://stackoverflow.com/a/4531233/11826257, I tried the solution below. But it only re-colors the word over which the mouse hovers.

<!DOCTYPE html>
<html>
  <head>
    <style>
      span.red_to_blue{color:red;}
      span.red_to_blue:hover{color:blue;}
      span.blue_to_red{color:blue;}
      span.blue_to_red:hover{color:red;}
    </style>
  </head>
  <body>
    <a href="#">
      <span class="red_to_blue">Hello</span>
      <span class="blue_to_red">World</span>
    </a>
  </body>
</html>

2

Answers


  1. Chosen as BEST ANSWER

    The comment from CBroe contains the solution: You can use a:hover followed by a CSS class selector. It is thus possible to define different behaviors for different classes. The classes can then be referred to in the html code, for example within a span element. The remodeled code looks like this:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          .red_to_blue{color:red;}
          .blue_to_red{color:blue;}
          a:hover .red_to_blue{color:blue;}
          a:hover .blue_to_red{color:red;}
        </style>
      </head>
      <body>
        <a href="#">
          <span class="red_to_blue">Hello</span>
          <span class="blue_to_red">World</span>
        </a>
      </body>
    </html>
    

  2. Did you try putting SPAN within SPAN?

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          span.red_to_blue{color:red;}
          span.red_to_blue:hover{color:blue;}
          span.blue_to_red{color:blue;}
          span.blue_to_red:hover{color:red;}
        </style>
      </head>
      <body>
        <a href="#">
          <span class="red_to_blue">Hello<span class="blue_to_red">World</span></span>
        </a>
      </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search