Search code examples
htmlcsscss-grid

CSS Grid Layout Sidebar toggle


This is a question regarding the new CSS Grid system that was recently added to the CSS web standards. This is an example of a layout that I am trying to use:

html,body{
  height: 100vh;
  width: 100wh;
  padding: 0;
  margin: 0;
  color: #e6e6e6;
}

body{
  display: grid;
  grid-template-columns: 9fr 300px;
  grid-template-rows: 50px auto 50px;
  grid-template-areas: "header header" 
                      "main chat"
                      "footer footer";
}

.chat{
  grid-area: chat;
  background-color: brown; 
  overflow: auto;
}
.header{
  grid-area: header;
  background-color: black;
}

.main{
  grid-area: main;
  background-color: maroon;
}

.footer{
  grid-area: footer;
  background-color: #222;
}
<div class="header">
    header
  </div>
  <div class="main">
    main
  </div>
  <div class="chat">
   chat
  </div>
  <div class="footer">
    footer
  </div>

Codepen example

Now I need to toggle the chat sidebar such that the main div occupies the remaining space. I already know how to do this in flexbox and JavaScript. However, I want to try this using CSS Grids.

One way would be to do this: grid-template-columns: 1fr 0;

But I want the chat sidebar to be toggled smoothly (like CSS transitions) rather than disappearing abruptly.


Solution

  • Make the grid adapt with auto, and change the .chat width

    html,body{
      height: 100vh;
      width: 100wh;
      padding: 0;
      margin: 0;
      color: #e6e6e6;
    }
    
    body{
      display: grid;
      grid-template-columns: 9fr auto;
      grid-template-rows: 50px auto 50px;
      grid-template-areas: "header header" 
                          "main chat"
                          "footer footer";
    }
    
    .chat{
      grid-area: chat;
      background-color: brown; 
      overflow: auto;
      width: 300px;
      transition: all 1s;
    }
    .header{
      grid-area: header;
      background-color: black;
    }
    
    .main{
      grid-area: main;
      background-color: maroon;
    }
    
    .footer{
      grid-area: footer;
      background-color: #222;
    }
    
    body:hover .chat {
    width: 0px;  
    }
      <div class="header">
        header
      </div>
      <div class="main">
        main
      </div>
      <div class="chat">
       chat
      </div>
      <div class="footer">
        footer
      </div>