Search code examples
cssgrid-layoutcss-grid

CSS grid - hide a grid-area on click of a button


I'm trying to create a sidenav that can be shown/hidden on a button click. I have used grid-area and grid-template-areas for the layout. I have a grid-area for sidenav. I want the grid-area also to be hidden when the sidenav is hidden. Is it possible to achieve this?

The full code is here - https://codepen.io/devi_ks/pen/Ebddwo

$("a").on("click", function() {
  $("#sidenav").hide();
  return false;
});
#header {
  grid-area: header;
  border: 1px solid red;
}

#sidenav {
  grid-area: sidenav;
  border: 1px solid green;
}

#content {
  grid-area: content;
  border: 1px solid black;
}

body {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 0.5fr 2fr;
  grid-template-areas: "header header" "sidenav content"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="header">
  <a href="#">Click me</a>
</div>
<div id="sidenav">
  <ul>
    <li> menu 1</li>
    <li> menu 2</li>
    <li> menu 3</li>
  </ul>
</div>
<div id="content">
  Some content goes here....
</div>


Solution

  • You use grid-area, so the place for the side nav is allocated at start. If you hide (or even delete) the side nav, that won't change anything about this. You have to do a little trick:
    Set the width for the first column to 0 and change the grid-gap because otherwise you will have a (not needed) gap at the left.

    $("a").on("click", function() {
      $("#sidenav").hide(true);
      $("body").css("grid-template-columns", "0px 2fr");
      $("body").css("grid-gap", "10px 0px");
      return false;
    });