0

I have 2 DIVs (DIV A and DIV B) inside a Flex container. Both DIVs should occupy the full width of the container. I want to hide and show DIV B with a smooth transition. I don't know what the size of DIV B is at a given moment, thus I'm using width in percentages for the width.

To hide DIV B I set it to "overflow:hidden" and "width:0%" but for some reason it would still occupy space next to DIV A. Why is this happening? I also observed that if I set the with in pixels (width:0px), DIV B does not use any space anymore and it seems to behave as I would expect it to behave, but in this case the transition is choppy.

Could somebody explain me what is happening here? Why are the percentages behaving differently in contrast to pixels in this case (While visually it seems to be doing what I'm asking it to do)

Here is an example I snipped together. When you click on the "Click to toggle DIV" box it will then toggle the hiding and showing of the problematic DIV. I'd expect the "Click to toggle DIV" to occupy the full with when the problematic DIV is hidden, but it does not.

Codepen version can be found here: Codepen

$('body').click(function(){
  $('.problematic-div').toggleClass('closed');
});
html, body {
     display: flex;
     flex-direction: column;
     height: 100%;
     margin: 0;
     padding: 0;
     color: white;
     cursor: pointer;
}
 .container {
     display: flex;
     flex-direction: row;
     height: 48px;
     background-color: grey;
}
 .container > .section-a {
     display: flex;
     flex-grow: 1;
     padding: 6px;
}
 .container > .section-a .section-a-div {
     display: flex;
     width: 100%;
     align-items: center;
     padding: 6px;
     background-color: #323130;
}
 .container > .section-b {
     display: flex;
     flex-direction: row;
}
 .container > .section-b .problematic-div {
     display: flex;
     flex-direction: row;
     align-items: center;
     white-space: nowrap;
     background-color: red;
     padding: 6px;
     overflow: hidden;
     max-width: 100%;
     opacity: 1;
     transition: max-width 0.3s ease-in-out, padding 0.3s ease-in-out, border 0.3s ease-in-out, opacity 0.3s ease-in-out;
}
 .container > .section-b .problematic-div.closed {
     max-width: 0%;
    /*max-width: 0;
     */
    /* This works for some reason */
     padding: 6px 0px 6px 0px;
     opacity: 0;
}
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="section-a">
    <div class="section-a-div">Click to toggle DIV</div>
  </div>
  <div class="section-b">
    <div class="problematic-div closed">
      <div>a very long text to showcase the issue</div>
    </div>
  </div>
</div>
Robert Koszewski
  • 583
  • 1
  • 8
  • 17

0 Answers0