绝对放置的容器未扩展宽度以适应Flexbox内容 [英] Absolutely positioned container not expanding width to fit flexbox content
问题描述
我在绝对定位的父 div
中有一个 flexbox
。我希望 flexbox
具有计算宽度
,从而导致父级div扩展,但这不会发生。父div具有一定的宽度,但是它的宽度不足以容纳flexbox。
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.
鉴于flexbox有四个子元素,每个子元素均具有 flex -basis:100px
和 flex-shrink:0
,我希望flexbox的宽度为 400px
,导致父div扩展到内容宽度的 400px
。相反,它正在扩展为看似任意的 255px
。
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>
推荐答案
您的代码在Edge中可用。
Your code works in Edge.
在Firefox和Chrome中不可用。
It doesn't work in Firefox and Chrome.
在这些浏览器中,这似乎是 flex-basis
的错误。
This appears to be a bug with flex-basis
in those browsers.
有一个简单的解决方法:使用 width
代替 flex-basis
。
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>
另请参见:
- What are the differences between flex-basis and width?
这篇关于绝对放置的容器未扩展宽度以适应Flexbox内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!