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!
4 Answers
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.
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.
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.
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.
Related Questions
Cloudflare Origin SSL Certificate Setup Guide
How To Effectively Monetize A Site With Ads