Search code examples
htmlcssdrop-down-menuopacityfade

Fade-in effect on a drop-down menu doesn't happen always


I want my drop-down menu to have a fade-in effect when mouse-hovered. I've written the following code for that, but the fade-in effect can be observed sometimes only, not always. Code:

* {
  margin: 0;
  padding: 0;
}

.header {
  position: fixed;
  list-style-type: none;
  height: 35px;
  width: 100%;
  background: #333333;
}

.header > li {
  display: inline-block;
  padding: 8px;
  position: relative;
  color: #FFF;
}

.header > li:hover {
  background: #000000;
}

.dropdown ul {
  list-style-type: none;
  display: none;
  position: absolute;
  top: 100%;
  left: 0;
  color: red;
  width: 100%;
  opacity: 0;
  background: yellow;
  border: 1px solid black;
  transition: opacity 1s;
}

.dropdown:hover ul {
  opacity: 1;
  display: block;
}
<ul class="header">
  <li class="home">Test</li>
  <li class="dropdown">Dropdown &#10097;
    <ul>
      <li>item 1</li>
      <li>item 2</li>
      <li>item 3</li>
    </ul>
  </li>
</ul>

I think the effect doesn't occur when I unhover and hover over "Dropdown ❱" within a second. I'm trying to do this using HTML and CSS only.

How can I achieve what I want?

BTW, How do I create a fade-out effect for the menu?


Solution

  • display is not an animatable property so you can use visibility instead of display.

    Here is the list of animatable-properties.

    * {
      margin: 0;
      padding: 0;
    }
    .header {
      position: fixed;
      list-style-type: none;
      height: 35px;
      width: 100%;
      background: #333333;
    }
    .header > li {
      display: inline-block;
      padding: 8px;
      position: relative;
      color: #FFF;
    }
    .header > li:hover {
      background: #000000;
    }
    .dropdown ul {
      list-style-type: none;
      /*display: none;*/
      visibility: hidden;
      position: absolute;
      top: 100%;
      left: 0;
      color: red;
      width: 100%;
      opacity: 0;
      background: yellow;
      border: 1px solid black;
      transition: visibility 1s, opacity 1s;
    }
    .dropdown:hover ul {
      opacity: 1;
      visibility: visible;
    }
    <ul class="header">
      <li class="home">Test</li>
      <li class="dropdown">Dropdown &#10097;
        <ul>
          <li>item 1</li>
          <li>item 2</li>
          <li>item 3</li>
        </ul>
      </li>
    </ul>