skip to Main Content

I have created a menu dropdown from the code below but when I hover over the dropdown button it works as expected. However, when I then hover over the dropdown itself (not the button) the menu keeps appearing. How can I make it so the menu dropdown would only appear when the button is hovered over?

.dropdown-content {
  position: absolute;
  z-index: 1;
  opacity: 0;
  visibility: none;
  transition: all .25s ease-in-out;
}
.dropdown:hover .dropdown-content {
  opacity: 1; 
  visibility: visible;
}
<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

2

Answers


  1. none isn’t a valid option for the visibility style. (Or at least a non-standard option?) The browser is essentially doing its best to fix the problem, and the result (at least for me) is that the element is there on the page (and thus hoverable) but not shown.

    Use visibility: hidden; instead of visibility: none;

    .dropdown-content {
      position: absolute;
      z-index: 1;
      opacity: 0;
      visibility: hidden;
      transition: all .25s ease-in-out;
    }
    .dropdown:hover .dropdown-content {
      opacity: 1; 
      visibility: visible;
    }
    <div class="dropdown">
      <button class="dropbtn">Dropdown</button>
      <div class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </div>
    Login or Signup to reply.
  2. simply use visibility : collapse; instead of visibility : none;

    also use this css for visibility:

    .dropbtn:hover + .dropdown-content ,
    .dropdown-content:hover {
    
    .dropdown-content {
      position   : absolute;
      z-index    : 1;
      opacity    : 0;
      visibility : collapse;
      transition : all .25s ease-in-out;
    }
    .dropbtn:hover  + .dropdown-content ,
    .dropdown-content:hover {
      opacity    : 1; 
      visibility : visible;
    }
    <div class="dropdown">
      <button class="dropbtn">Dropdown</button>
      <div class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search