Anthony Flora Anthony Flora - 1 month ago 9
CSS Question

How can I change the background-color of a div inside a link

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>

Answer Source

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>