I created this snippet
.wrapper {
position: fixed;
inset: 0;
display: flex;
justify-content: center;
padding-top: 15px;
padding-bottom: 15px
}
.modal {
width: 300px;
display: flex;
flex-direction: column;
}
.container {
flex: 1;
display: flex;
flex-direction: column;
}
.footer {
height: 50px;
background-color: red;
}
.content {
flex: 1 1 0px;
overflow-y: scroll;
}
.box {
height: 300px;
}
.box-yellow {
background-color: yellow;
}
.box-blue {
background-color: blue;
}
<div class="wrapper">
<div class="modal">
<span>heading</span>
<div class="container">
<div class="content">
<div class="box box-yellow"></div>
<div class="box box-blue"></div>
</div>
<div class="footer"></div>
</div>
</div>
</div>
The goal is to create a modal with a header, scrollable content and a footer.
The order of the markup is required as is.
My question is why does it have to be:
.content {
flex: 1 1 0px;
overflow-y: scroll;
}
Why can’t it just be:
.content {
flex: 1;
overflow-y: scroll;
}
The final goal is achieved but as a beginner in flexbox, I would like to know why flex: 1 1 0px
is needed.
I have read some documentation about flex-basis, but it looks like flex-basis has several behaviors. What is going in this specific case?
2
Answers
This is actually a little tricky; it is a bit buried in the spec, but the default flex basis (when omitted in a
flex
declaration) is0%
.For your case,
0%
means nothing, because the parent doesn’t have a specified height (similarly,height: 0%
wouldn’t mean anything). This causes it to be ignored, and it falls back toauto
, which ends up expanding the whole thing.Setting it to
0px
on the other hand works, because it can properly be resolved and so actually takes effect.flex: 1
is equivalent to:flex-grow: 1
flex-shrink: 1
flex-basis: auto
With
flex-basis: auto
(content-based length), the container will simply shrink and expand to accommodate the height or width of the content. There is no limit that would trigger a scrollbar.With
flex-basis: 0px
, you are setting a defined length, which is enough to trigger a scrollbar (in conjunction withflex-grow: 1
, in this case).By the way, you don’t even need to define the
px
units.flex-basis: 0
is enough.But don’t use percentage units (
%
), as that would cause the scrollbar to fail, as you would need to define lengths on parent containers.