【问题标题】:Absolutely positioned container not expanding width to fit flexbox content [duplicate]绝对定位的容器没有扩展宽度以适应弹性框内容[重复]
【发布时间】:2020-03-29 21:14:41
【问题描述】:

我在绝对定位的父 div 中有一个 flexbox。我希望flexbox 有一个computed width,导致父 div 扩展,但这不会发生。父 div 有一些宽度,但宽度不足以容纳 flexbox。

鉴于 flexbox 有四个孩子,每个孩子都有 flex-basis: 100pxflex-shrink: 0,我希望 flexbox 的宽度为 400px,导致父 div 扩展为内容宽度的 400px .相反,它扩展为看似任意的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>

【问题讨论】:

    标签: html css flexbox css-position


    【解决方案1】:

    您的代码在 Edge 中运行。

    它在 Firefox 和 Chrome 中不起作用。

    这似乎是这些浏览器中flex-basis 的错误。

    有一个简单的解决方法:使用width,而不是flex-basis

    .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

    另见:

    【讨论】:

    • 如果父级恰好比 flexbox 宽,我希望 flexbox “增长”(这是基于 flex: **1** 0 100px 的预期行为)。
    • flex-grow: 1 添加到.flex-child 类。 jsfiddle.net/k0gxLw3z
    • flex-basiswidth 可以互换(在行方向上)。似乎 flex-basis 没有被 Chrome 和 FF 正确处理。所以请改用width。其他 flex 属性——flex-growflex-shrink——仍然可以以它们的普通形式使用。
    • 效果很好。就在我花了一个小时将其转换为表格之后..现在我将其转换回来。用flex-grow: 1 更新你的答案,我很乐意接受!谢谢。
    • 只是出于好奇——我有什么方法可以编辑你的 sn-p 来测试东西吗?我知道你提供了一个 jsFiddle,但有时我只遇到了 sn-ps 的答案,这让我无法使用 sn-ps 感到愤怒。
    【解决方案2】:

    使元素适合绝对定位元素的唯一方法是更改​​以下行

    .flex-child {
        flex: 1 1 100px;
        ...
    }
    

    之后.flex 元素占据了.parent 元素,如果我增加任何宽度,红色区域就会扩大。

    这对你有用吗?

    【讨论】:

    • 问题是要求父级扩展到内容的宽度,而不是相反。
    • 因为它有flex-shrink: 1,所以它不会强制每个flexchild 的最小宽度为100px。如上所述,我希望使用这个最小宽度来拉伸父级的宽度(如果父级不够宽)。
    猜你喜欢
    • 2015-06-14
    • 2023-03-11
    • 1970-01-01
    • 2017-01-04
    • 2012-02-11
    • 2018-03-23
    • 2018-02-13
    • 1970-01-01
    • 2014-04-29
    相关资源
    最近更新 更多