简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM