问题
I have a flexbox
inside of an absolutely positioned parent div
. I expect the flexbox
to have a computed width
, causing the parent div to expand, but this doesn't happen. The parent div has some width, but it is not wide enough to accommodate the flexbox.
Given that the flexbox has four children, each with flex-basis: 100px
, and flex-shrink: 0
, I'd expect the flexbox to have a width of 400px
, causing the parent div to expand to 400px
of content width. It is instead expanding to a seemingly arbitrary 255px
.
.parent {
position: absolute;
padding: 10px;
background: red;
}
.flex {
display: flex;
}
.flex-child {
flex: 1 0 100px;
background: #EEE;
border: 1px solid black;
white-space: nowrap;
overflow: hidden;
}
<div class="parent">
<div class="flex">
<div class="flex-child">One</div>
<div class="flex-child">Two</div>
<div class="flex-child">Three (really really long)</div>
<div class="flex-child">Four</div>
</div>
</div>
回答1:
Your code works in Edge.
It doesn't work in Firefox and Chrome.
This appears to be a bug with flex-basis
in those browsers.
There's a simple workaround: Instead of flex-basis
, use width
.
.parent {
position: absolute;
padding: 10px;
background: red;
}
.flex {
display: flex;
}
.flex-child {
/* flex: 1 0 100px; */
width: 100px;
flex-grow: 1;
flex-shrink: 0;
background: #EEE;
border: 1px solid black;
white-space: nowrap;
overflow: hidden;
}
<div class="parent">
<div class="flex">
<div class="flex-child">One</div>
<div class="flex-child">Two</div>
<div class="flex-child">Three (really really long)</div>
<div class="flex-child">Four</div>
</div>
</div>
jsFiddle demo
Also see:
- What are the differences between flex-basis and width?
回答2:
The only way I was able to make the elements fit the absolutely positioned element was to change the following line
.flex-child {
flex: 1 1 100px;
...
}
After that the .flex
element occupied the .parent
element and if I increased any widths the red area expands.
Does that work for you?
来源:https://stackoverflow.com/questions/59186681/absolutely-positioned-container-not-expanding-width-to-fit-flexbox-content