Imagine having a collapsible fixed-width sidebar like this:
HTML
<div class="container">
<div class="sidebar" id="sidebar">
SIDEBAR
</div>
<div class="content">
lorem bla bla
<button onclick="document.getElementsByClassName('sidebar')[0].classList.toggle('collapsed')">
toggle Sidebar
</button>
</div>
</div>
CSS
body {
margin:0;
}
.container {
display: flex;
min-height:100px;
}
.sidebar {
position: relative;
left: 0;
width: 200px;
background-color: #ccc;
transition: all .25s;
}
.sidebar.collapsed {
left:-200px;
margin-right:-200px;
}
Codepen link: http://codepen.io/anon/pen/pJRYJb
Now, the question arises:
How can we transform this into a flexible-width sidebar?
Here are the key requirements:
- Avoid using JavaScript for layouting
- Ensure that the sidebar does not overlap the content
- When collapsed, align the sidebar's right border with the window's left border
- Maintain constant sidebar width even when collapsed to prevent reflows during transitions
- Create smooth transitions without abrupt movements
- Utilize modern CSS features like flexbox and calc
The challenge lies in finding a way to set margin-right: -100%
, where 100%
represents the sidebar's width
Your assistance is highly appreciated!