Search code examples
htmlcssstylesheet

Create a navigation list that changes its image on hover,but it doesn't work


HTML

<ul id="NavList">
    <li id="Home"><a href="Second.aspx"></a></li>
    <li id="About"><a href="Second.aspx"></a></li>
</ul>

CSS:

#Home {
    background: url('NavIcons/1.gif');
}
#Home a:hover {
    background: url('NavIcons\2.gif');
}

I am creating a navigation list that changes its image on hover, but it doesnt work.


Solution

  • If you want to show the background change of #Home or #About when hovering only on a then you can use the following:

    HTML

    <ul id="NavList">
        <li id="Home"><a href="Second.aspx">1</a><div></div></li>
        <li id="About"><a href="Second.aspx">2</a><div></div></li>
    </ul>
    

    CSS

    #Home,#About {
        position:relative;
        width:70px;
        height:50px;
    }
    #Home div, #About div{
        position:absolute;
        background: url('https://i.sstatic.net/2JzQz.jpg');
        background-position:-20px 0px;
        top:0px;
        width:100%;
        height:100%;
    }
    #Home a,#About a{
        position:absolute;
        top:20px;
        left:20px;
        z-index:100;
    }
    #Home a:hover+div , #About a:hover+div{
        background: url('https://i.sstatic.net/7rx8G.jpg');
        background-position:-20px 0px;
    }
    

    Demo


    Got this idea from How to style the parent element when hovering a child element? .My CSS is different but using same idea.