Absolutely positioned container not expanding width to fit flexbox content [duplicate]

岁酱吖の 提交于 2020-01-14 03:26:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!