How to Add CSS Transition for a Dropdown Menu After Changing Display from None?
Asked by
poster tube 2
I'm working on a desktop navigation menu, where some items have dropdown sub-menus. My challenge is that after changing the parent div of the sub-menu from display:none to display:flex, I want to apply a CSS transition to it. Since transitions won't work on elements that are display:none, I need help figuring out how to manage this effectively. I've tried several JavaScript approaches including using mouse events, a mutation observer, and even setTimeout to apply styles after the display change. None have been successful so far, so any suggestions would be highly appreciated!
Answers
Usually, transitioning doesn't work on display. Instead, you should transition the opacity and use pointer-events to ensure the invisible menu isn't clickable. Also, if you add a CSS hover effect on the item itself, you can control the visibility of the submenu without having to rely on JS.
Reply to this answer
Consider keeping the submenu wrapper in the DOM at all times. You can use CSS to hide it with opacity and visibility but keeping it there eases the transition. Toggle a class on hover to animate it. Like setting opacity to 0 initially and then changing it to 1 on hover. This prevents the issues with display:none.
Reply to this answer
Definitely don't use display:none! It removes the element from the flow, while visibility:hidden keeps it in place. You can manage it with visibility and opacity to get smooth transitions without disrupting screen readers.
Reply to this answer
You might want to explore the `@starting-style` or `animation` attribute with 'forwards' set as suggested. It can help with transitions from display:none! Here's a resource that covers it well: https://nerdy.dev/using-starting-style-and-transition-behavior-for-enter-and-exit-stage-effects.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions