Hannah Holt Hannah Holt - 3 months ago 11
CSS Question

Make absolute element sit directly below relative element

I'm currently building a dropdown nav bar that activates upon hover.

I would like the dropdown nav to display directly under the PORTFOLIO link when hovered over, it's currently displaying over to the right.

Styling and what not is going to come later, I wanted this bit sorted before carrying on.

<div class="twelve columns">
<ul class="navigation six columns offset-by-three">
<li><a href="#">HOME</a></li>
<li><a href="#" class="submenu">PORTFOLIO</a></li>
<div class="sub-hover">
<a href="">Photos</a>
<a href="">Physical</a>
<a href="">Write</a>
<a href="">Studies</a>
</div>
<li><a href="#">ABOUT</a></li>
<li><a href="#">CONTACT</a></li>
</ul>
</div>






.navigation {
display: flex;
flex-direction: row;
justify-content: center;

}

.navigation li {
display: inline-block;
padding: 10px 20px;
}

.submenu {
position: relative
}

.sub-hover {
position: absolute;
display:;
margin-top: 25px;
padding: 5px 10px;

}

.sub-hover a {
display: block;
}

.submenu:hover .sub-hover {
display: block;
}




Answer

There are a couple things you need to change:

  1. You need to place your .sub-hover inside of the portfolio <li> instead of outside of it.
  2. Display your .sub-hover div when .submenu is hovered. You can accomplish this by using the CSS sibling selector ~.
  3. Display your .sub-hover div when the div itself is hovered.
  4. In your .sub-hover div, use padding instead of margin so the div won't disappear when you move your mouse from the title to the dropdown.

CSS

.sub-hover {
    padding-top: 25px;
}

.submenu:hover ~ .sub-hover {
    display: block;
}

.sub-hover:hover {
    display: block;
}

.navigation {
    display: flex;
    flex-direction: row;
    justify-content: center;
    
}

.navigation li {
    display: inline-block;
    padding: 10px 20px;
}

.submenu {
    position: relative
}

.sub-hover {
    position: absolute;
    display:;
    padding-top: 25px;
    padding: 5px 10px;
    display: none; 
}

.submenu:hover ~ .sub-hover {
  display: block;
}

.sub-hover:hover {
  display: block;
}

.sub-hover a {
    display: block;
}

.submenu:hover .sub-hover {
    display: block;
}
<div class="twelve columns">
          <ul class="navigation six columns offset-by-three">
              <li><a href="#">HOME</a></li>
              <li><a href="#" class="submenu">PORTFOLIO</a>
                  <div class="sub-hover">
                    <a href="">Photos</a>
                    <a href="">Physical</a>
                    <a href="">Write</a>
                    <a href="">Studies</a>
                  </div>
              </li>
              <li><a href="#">ABOUT</a></li>
              <li><a href="#">CONTACT</a></li>
          </ul>
      </div>

Comments