0

I'm building a dropdowns menu that appears when hovering the mouse over the title. Although I followed some instruction on w3schools, my code doesn't work and I don't know why and how to fix it. All answers is appreciated. Here is my code:

.dropdown {
  display: block;
  position: relative;
}
.dropdown-content {
  display: none;
  width: 100%;
  position: absolute;
}
.dropdown:hover .dropdown-content {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>

  <div class="menu">
    <h2 class="dropdown">Menu</h2>
    <div class="dropdown-content">
      <ul>
        <li>
          <a href="#">Content</a>
        </li>
        <li>
          <a href="#">Content</a>
        </li>
        <li>
          <a href="#">Content</a>
        </li>
        <li>
          <a href="#">Content</a>
        </li>
      </ul>
    </div>
  </div>

</body>

</html>

3 Answers 3

1

You need to write the hover styles on the wrapper i.e. <div class="menu">...</div> because the element <div class="dropdown-content">...</div> is a descendant of it.

Also give display: inline-block; to the element that is used to open the drop down menu here it is the <h2 class="dropdown">Menu</h2> doing so will keep the drop down menu open when the cursor is over it allowing the user to pick an option.

Check the below code snippet.

.dropdown {
  display: inline-block;
  position: relative;
  margin: 0;
}
.dropdown-content {
  display: none;
  position: absolute;
}
.menu:hover .dropdown-content {
  display: block;
}
<div class="menu">
  <h2 class="dropdown">Menu</h2>
  <div class="dropdown-content">
    <ul>
      <li>
        <a href="#">Content</a>
      </li>
      <li>
        <a href="#">Content</a>
      </li>
      <li>
        <a href="#">Content</a>
      </li>
      <li>
        <a href="#">Content</a>
      </li>
    </ul>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

aha...I got it! Thanks a lot!
0

well a sneaky bug there

.dropdown:hover+.dropdown-content {
    display: block;
}

.dropdown and .dropdown-content

they are siblings not parent child

indentation of your html is deceiving

1 Comment

well...the editor make it quite hard to get a perfect indentation...at least for me... Thank you, any way!
0

Try this codepen...

Actually what you are doing mistake is you have to show the sibling of your heading on hover what you are doing is.dropdown:hover .dropdown-content {display: block;} to apply styles to sibling we have to use + like tthis .dropdown:hover + .dropdown-content {display: block;}.

hope you understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.