2

Is it possible to change the background-color of a div inside a link using only a :visited pseudo class and without using Javascript?

<!DOCTYPE html>
<html>
    <head>
      <style>
            a:hover {background-color:blue;}
            a:visited {background-color:green;}

           .smallbox {
            background-color: #666;
            height: 50px;
            width: 50px;
           }
           .smallbox:hover {background-color:blue;}
           .smallbox:visited {background-color:green;}
      </style>
    </head>
    <body>
        <a href="#"><div class="smallbox"></div></a>
    </body>
</html>

2 Answers2

1

Yes, I believe you can do this. Just remember the visited pseudo class belongs to the link, not the div.

a:hover .smallbox {background-color:blue;}
a:visited .smallbox {background-color:green;}
a:visited .smallbox:hover {background-color:blue;}

 .smallbox {
  display: block;
  background-color: #666;
  height: 50px;
  width: 50px;
 }
 
<a href="##"><span class="smallbox"></span></a>

As pointed out by Dekel in the comments, a div inside an anchor element is invalid HTML. You could cheat and put a span inside the link and set its display property to "block", but that's probably not really better.

If you just need a link that behaves like a block element rather than an inline element, consider switching the anchor tag's display property to block and removing the inner element entirely as suggested in this post: <div> within <a>

0

Instead of applying it to a div, why not apply it directly to the "a" tags, as you did, and remove the div? Why do you need it? a: hover { background-color:blue; } should work just fine. You just need to add a display:block to the a:hover style, as well.

Or, if you have multiple a tags on the page and only want to apply it to one of them, you can use an id and apply it to that:

<a id="someId" href="#">My Link</a>

CSS:

#someId {
    background-color: blue;
    display: block;
}
vapcguy
  • 7,097
  • 1
  • 56
  • 52