htmlcssflexbox

Make flex container shrink with children


I have a Flexbox container, which has two items where one of them collapses on clicking the container. The second item collapses perfectly fine and the first item takes up the remaining space.

However the .flexbox-container keeps its size (the red background of the container is visible when item2 collapses). How can I make the container also shrink to adjust to the children's (in this case only the remaining item1) size (i.e. the red background shouldn't be visible anymore)?

let isExpanded = false
$(".flex-container").on("click", function () {
  if (isExpanded === false) {
    isExpanded = true
    $("#item2").addClass("collapsed")
  } else {
    isExpanded = false
    $("#item2").removeClass("collapsed")
  }
})
body {
  font-size: 25px;
}

.flex-container {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: red;
}

.flex-collapsible {
  overflow: hidden;
  flex: 1;
  transition: flex 0.5s cubic-bezier(0.2, 0.4, 0.4, 1.0);

  &.collapsed {
    flex: 0;
  }
}

#item1 {
  background-color: yellow;
}

#item2 {
  background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="flex-container">
  <div id="item1">fixed</div>
  <div class="flex-collapsible" id="item2">collapsible</div>
</div>


Solution

  • I would consider CSS grid and animate grid-template-columns

    $(".flex-container").on("click", function () {
      $(this).toggleClass("collapsed")
    })
    body {
      font-size: 25px;
    }
    
    .flex-container {
      display: inline-grid;
      grid-template-columns: auto 1fr;
      transition: grid-template-columns 0.5s cubic-bezier(0.2, 0.4, 0.4, 1.0);
      overflow: hidden;
      align-items: center;
      justify-content: center;
      background-color: red;
      &.collapsed {
         grid-template-columns: auto 0fr;
      }
    }
    
    #item1 {
      background-color: yellow;
    }
    
    #item2 {
      background-color: orange;
      min-width: 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="flex-container">
      <div id="item1">fixed</div>
      <div class="flex-collapsible" id="item2">collapsible</div>
    </div>