使用max-height实现下拉菜单隐藏的问题排查
Hey there! Let's sort out your dropdown issue right away. The core problem here is twofold: when you set max-height: 0 on the .content element, you didn't restrict overflow—so content still spills out even when the max-height is zero. And when you switched to height, while it hides content, you lose smooth transitions because CSS can't animate to/from an auto height value.
Here's the straightforward fix:
- Add
overflow: hiddento the base.contentclass — this tells the browser to clip any content that exceeds the element's max-height, making it truly hidden when collapsed. - Stick with
max-heightfor transitions — it’s the right approach here because it lets you animate between two concrete values (0 and your65vhactive state), while still adapting to variable content heights.
Modified .content CSS:
.content { position: absolute; top: 0; display: block; z-index: 1; max-height: 0; width: 100%; padding-top: 30px; transition: max-height 0.4s linear; overflow: hidden; /* This line fixes the persistent visibility */ }
Why this works:
overflow: hiddenis the missing piece—without it, content flows outside the element’s bounds even whenmax-height: 0is applied. This clips the content exactly to the element’s calculated height.- Using
max-heightinstead ofheightkeeps the transition smooth because we’re animating between fixed values (0 and 65vh). The browser can easily calculate the animation path, even if your actual content height is shorter than 65vh.
A quick UX improvement:
Update the .active state to use overflow: auto instead of scroll—this way, the scrollbar only appears when content actually exceeds 65vh, which feels more polished:
.content.active { z-index: 3; max-height: 65vh; overflow: auto; /* Only show scrollbar when needed */ }
Testing the fix:
Now when you toggle the active class, your dropdown will smoothly expand from a hidden state (max-height: 0) to its full height, and collapse back cleanly—no more persistently visible content!
内容的提问来源于stack exchange,提问作者user9294038

