cameraguy258
cameraguy258

Reputation: 689

Transition menu closing with CSS or JS

I have a sidebar div and a content div that act as two CSS grid columns. The sidebar itself is composed of two more columns, but here's the gist of the setup:

<div class='site-wrap'>
    <div class='sidebar'>
        <div class='navbar'></div>
        <div class='menu'>
            <ul>
                <li>menu item</li>
            </ul>
        </div>
    </div>
    <div class='content>
        <h1>Hello world</h1></div>
    </div>
</div>

Most of the CSS isn't important, but here's how the sidebar works:

.site-wrap {
    display: grid;
    grid-template-columns: 320px 1fr;
}

.sidebar {
    display: grid;
    grid-template-columns: 64px 1fr;
    height: 100vh
}

Here's a JS Fiddle with a working implementation: https://jsfiddle.net/z4mLtwoy/

Currently, my solution to closing the menu is adding grid-template-columns: 72px 1fr to the site-wrap. This works, but I wish to add a transition. Since CSS grid doesn't have transitions yet, is there a CSS (maybe flexbox) or JS implementation that can offer a transition?

Upvotes: 0

Views: 343

Answers (1)

ElChiniNet
ElChiniNet

Reputation: 2902

If you set a width or a max-width property to the menu element, it is possible to animate this property using CSS transitions. No need to use grids, you can use a flexbox layout to display them as columns.

body {
  margin: 0;
  padding: 0;
}

.site-wrap {
  display: flex;
  height: 100vh;
}

.sidebar {
  display: flex;
}

.site-wrap .menu {
  box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
  box-sizing: border-box;
  height: 100vh; 
  margin: 0;
  overflow: hidden;
  padding: 0;
  transition: max-width 0.5s ease;
  max-width: 100px;
}

.site-wrap .navbar {
  background: green;
  height: 100vh;
  width: 64px;
}

.menu li {
  padding: 16px;
  white-space: nowrap;
}

.content {
  background: #EFEFEF;
  box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
  flex-grow: 1;
  padding: 16px;
}

.banner {
  background: lightblue;
  box-sizing: border-box;
  padding: 16px;
  height: 64px;
  width: 100%;
}

#trigger {
  display: none;
  position: fixed;  
}

.button {
  background: blue;
  color: white;
  cursor: pointer;
  margin: 8px;
  padding: 8px 16px;  
}

#trigger:checked ~ .site-wrap .menu {
  max-width: 0px;
}
<input id='trigger' type='checkbox'>
<div class='banner'>
  <label for='trigger' class='button'>Click me</label>
</div>
<div class='site-wrap'>
  <div class='sidebar'>
    <div class='navbar'></div>
    <ul class='menu'>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
    </ul>
  </div>
  <div class='content'>
    <h2>Hello world</h2>
  </div>
</div>

Upvotes: 1

Related Questions