Search code examples
csscss-gridcss-transformsexpand

CSS Grid content-area horizontally expansion for filling the container


I have a CSS Grid container and a sidebar and content area inside it. I want to when user close the sidebar, content area, horizontally expands to fill the whole width of the container. I've used transformX(-100%) on hover the sidebar for hiding and transformX(0%) for showing the sidebar on mouse out in my bellow sample:

.test-container {
  display: grid;
  background-color: aquamarine;
  grid-template-columns: 1fr 2fr;
  grid-template-areas: "sidebar content";
  height: 100vh;
}

.test-sidebar {
  background-color: blue;
  grid-area: sidebar;
  transform: translateX(0%);
  font-size: 40px;
  color: white;
  text-align: center;
  transition: 2000ms;
}

.test-sidebar:hover {
  transform: translateX(-100%);
  transition: 2000ms;
}

.test-content {
  background-color: blueviolet;
  font-size: 40px;
  text-align: center;
  grid-area: content;
  color: white;
}
<div class="test-container">
  <div class="test-sidebar">Sidebar</div>
  <div class="test-content">Content</div>
</div>


Solution

  • Here is a solution with hovering on all grid element, just to demonstrate, how we can act with two different cells. Here we have grid-template-columns: auto 1fr; in .test-container and static width in .test-sidebar. Now they are expanding/collapsing like you want.

    About other behave, what does it mean "when user close the sidebar"? Describe this action pleas. Describe both behave of the sidebar, in which case it should collapse and expand? I think, the whole solution will requires JS. I will add it after your description, if needed.

    .test-container {
      display: grid;
      background-color: aquamarine;
      grid-template-columns: auto 1fr;
      height: 100vh;
      transition: all 2s ease;
    }
    
    .test-sidebar {
      background-color: blue;
      font-size: 40px;
      color: white;
      text-align: center;
      overflow: hidden;
      width: 200px;
      transition: all 2s ease;
    }
    
    .test-container:hover .test-sidebar {
      width: 0;
    }
    
    .test-content {
      background-color: blueviolet;
      font-size: 40px;
      text-align: center;
      color: white;
    }
    <div class="test-container">
      <div class="test-sidebar">Sidebar</div>
      <div class="test-content">Content</div>
    </div>