CSS transition does not apply to element even when its opacity is changing

Viewed 31

I believe that setting a transition on an element should mean that when its style changes (in this case from opacity: 0 to opacity: 1 that the specified transition should run. However, I'm finding in my case it does not it simply "appears".

https://codepen.io/asos-francesca/pen/xxOroON

I am adjusting the opacity of the element by way of its parent receiving a hover, could this be the reason why it doesn't work?

.submenu {
  display: none;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
  transition-delay: 0.2s;
}
  
.hoverable:hover .submenu {
  display: block;
  opacity: 1;
}
2 Answers

Changing display from none to hidden allows the transition to take place. However, you're still left with the issue of the background. It's not exactly clear what you want the end effect to be?

To complete with the answer of mah111, you could use absolute position to your submenu. I rewrite your code like this for example :

<nav class="hoverable">
  <div>
    Hover me
  <div/>

  <ul class="submenu"><li>Item</li></ul>
</nav>

And the css :

.submenu {
  display: hidden;
  position: absolute;
  width:100%;
  background-color: pink;
  opacity: 0;
  padding-left: 20px;
  top: 22px;
  left: 0;
  transition: all 0.5s ease-in-out 0.5s;
}

.hoverable {
  cursor: pointer;
  padding: 10px;
  background-color: pink;
  display: inline-block;
  position: relative;
}
  
.hoverable:hover .submenu {
  display: block;
  opacity: 1;
}

And if you have multiple main categories with submenus, you should contain each main category and submenu in separate container (but togheter in a same nav for example) to adjust easily the absolute position.

Related