Simon Simon - 4 months ago 18
CSS Question

Flexbox overflow when the container reach minimum size

I have a flex column container with 2 div inside. The first div have

flex: 1
to make it grow with the remaining space. The second div have a fixed height. Note that the container is inside a fixed div taking the whole viewport.

The problem is that when the container is too small to fit the content, the first div's content overflow under the second one.



.test {
position: fixed;
top: 0;
left: 0;
right: 0;
background-color: red;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
//min-height: 500px;
}
.child1 {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
}
.child2 {
width: 100%;
display: flex;
justify-content: center;
}
span {
padding: 20px;
}
span:first-child {
margin-top: auto;
}
span:last-child {
margin-bottom: auto;
}

<div class="test">
<div class="child1">
<span>Test1</span>
<span>Test2</span>
<span>Test3</span>
<span>Test4</span>
<span>Test5</span>
<span>Test6</span>
<span>Test7</span>
<span>Test8</span>
</div>
<div class="child2">
<span>Test1</span>
<span>Test2</span>
<span>Test3</span>
<span>Test4</span>
</div>
</div>





Here is a codepen example.

One solution could be to set a minimum height on the container, but it's not a dynamic and responsive solution.

Can someone tell me how to achieve an overflow behavior on the container when the whole content does not fit?

Answer

you may add overflow:auto to .test and update flex value on .child1: DEMO to play with

.test {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: red;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow:auto;/* update */
}

.child1 {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content:center;/* update (IE)*/
  flex: 1 0 auto;/* update */
}

.child2 {
  width: 100%;
  display: flex;
  justify-content: center;
}

span {
  padding: 20px;
}

span:first-child {
  margin-top: auto;
}

span:last-child {
  margin-bottom: auto;
}
<div class="test">
  <div class="child1">
    <span>Test1</span>
    <span>Test2</span>
    <span>Test3</span>
    <span>Test4</span>
    <span>Test5</span>
    <span>Test6</span>
    <span>Test7</span>
    <span>Test8</span>
  </div>
  <div class="child2">
    <span>Test1</span>
    <span>Test2</span>
    <span>Test3</span>
    <span>Test4</span>
  </div>
</div>

Comments