Trying to design a basic page layout with a collapsible menu next to the main content. Seeking a way to smoothly collapse the menu for a better user experience.
To illustrate, consider this example:
<div id="container">
<div id="menu">
<div id="toggle" onclick="document.getElementById('menu').classList.toggle('collapsed')">X</div>
<div class="content">Menu content</div>
</div>
<div class="content">Main content goes here</div>
</div>
Functionality-wise, clicking the X toggles the menu as expected, but the abrupt transition is not ideal. How can we achieve a smoother closing effect?
One approach involves setting a specific width
for the menu and utilizing a transition: width
property in the stylesheet:
The modified CSS code is as follows:
<div id="container">
<div id="menu">
<div id="toggle" onclick="document.getElementById('menu').classList.toggle('collapsed')">X</div>
<div class="content">Menu content</div>
</div>
<div class="content">Main content goes here</div>
</div>
However, this solution has some limitations:
Difficulty in determining the initial width (
100px
here). Would prefer a dynamic width based on the content size. Removingwidth: 100px
breaks the transition, andwidth: 100%
does not work properly either.During menu closure, text reflows which appears unattractive. Looking for ways to avoid this issue.
Potential inefficiency of maintaining a zero-width menu in the DOM compared to using
display: none
, as rendering may still occur.
Seeking alternative methods to animate the opening and closing of the menu for a seamless experience.
(Referenced a similar question here: Collapsible flexible-width sidebar using only CSS. This suggests using max-width
instead of width
, resolving one issue but introducing a transition delay when max-width is high.)