Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hovering over navigation link to show a separate div

Tags:

html

css

What I want to do is have a link called 'Weather' in my navigation bar, and when you hover over it or click it, I want it to show a dropdown with the weather network widget inside of it.

This is what I have so far. The hover part works, however it pushes the 'weather' link to the bottom of my navigation bar. How do I get it to resume its original position?

    <div id="navbar"> 
        <ul> 
            <li><a href="#">Home <img src="home.png" /></a></li> 
            <li><a href="#">Forum <img src="forum.png" /></a></li> 
            <li><a href="#">Pictures <img src="camera.png" /></a></li> 
            <li><a href="#">Videos <img src="videos.png" /></a></li> 
            <li><a href="#">Technology <img src="technology.png" /></a></li>
            <li><a href="#">Politics <img src="politics.png" /></a></li> 
            <li><a href="#">World Issues <img src="issues.png" /></a></li> 
            <li><a href="#">Contact <img src="contact.png" /></a> 
            <li><a href="#"><div id="div1">Weather <img src="weather.png" /></a><div id="div2">testing</div></div></li> 
        </ul> 
    </div> 

And the CSS:

#div1 {
    cursor:pointer;
 }
#div2 {
    display:none;
    height: 20px;
    width: 100px;
    background-color: white;
    position: absolute;
    top: 100px;
    left: 100px;
    z-index: 20;
 }
#div1:hover #div2 {
    display:block;
 }

Here is an image of what it looks like.

like image 880
user3107811 Avatar asked Nov 01 '22 08:11

user3107811


1 Answers

First, you should fix your HTML. Replace your divs line with this (I am reformatting it for the sake of the readability of my answer):

<li id="div1">
    <a href="#">Weather <img src="weather.png" /></a>
    <div id="div2">testing</div>
</li> 

And then, try this CSS code:

#div1 {
    position: relative;
}
#div1 > a {
    cursor:pointer;
}
#div2 {
    position: absolute;
    top: 100%;
    left: 0;

    display:none;
    height: 20px;
    width: 100px;
    background-color: white;
    z-index: 20;
 }
 #div1:hover #div2 {
    display:block;
 }

It works because when you place an absolute positioned element inside a relative positioned element, the absolute element will position itself according to the bounds of the relative element. Therefore, top: 100% will place #div2's top at the bottom of #div1.

like image 196
Ben Barkay Avatar answered Nov 16 '22 15:11

Ben Barkay