【问题标题】:Make flex container expand and overflow its container使 flex 容器扩展并溢出其容器
【发布时间】:2016-08-18 21:09:29
【问题描述】:

我如何使用 nowrap flex-wrap 扩展以适应其内容的 flex 父级,即使这意味着溢出包裹父级的任何内容?

基本上,内容有一个最小宽度,我希望 flex 父级不会缩小超过所有 flex 项所需的空间。

这是一个 JSFiddle https://jsfiddle.net/lazamar/odat477r/

.wrapper {
  background-color: yellowgreen;
  display: block;
  padding: 10px;
  max-width: 180px;
}

.parent {
  display: flex;
  flex-flow: row nowrap;
  background-color: yellow;
}

.child {
  display: block;
  background-color: orange;
  margin: 10px;
  min-width: 50px;
}
<div class="wrapper">
  <div class="parent">
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
  </div>
</div>

【问题讨论】:

  • 您希望.parent 的宽度与其子项的总和相同?
  • 是的。不仅要考虑孩子的宽度,还要考虑他们的边距和父母的内边距。
  • 那么你应该在你的.parent 上使用display:inline-flex 而不是display: flex。您还需要删除min-width

标签: html css flexbox


【解决方案1】:

使用display: inline-flex 代替display: flex 是您最好的选择。

如果出于任何原因,这不是一个选项,请使用 CSS 定位属性。

.wrapper {
  background-color: yellowgreen;
  display: block;
  padding: 10px;
  max-width: 180px;
  position: relative;             /* new; set bounding box for flex container  */
  min-height: 40px;               /* new */
}

.parent {
  display: flex;
  flex-flow: row nowrap;
  background-color: yellow;
  position: absolute;             /* new; remove flex container from document flow */
}

.child {
  /* display: block;              <-- not necessary */
  background-color: orange;
  margin: 10px;
  min-width: 50px;
}
<div class="wrapper">
  <div class="parent">
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
  </div>
</div>

【讨论】:

  • 类似问题并尝试了您的解决方案,但没有运气。我不能在孩子上设置最小宽度,它应该是动态 flex 容器在一个固定宽度的容器内我想随着孩子的成长而扩展 flexbox jsfiddle.net/shankarregmi/az7vqoup/3 我希望红色背景覆盖整个内容
  • .menu-list加红色背景怎么样? jsfiddle.net/kzu1qa8h@ShankarRegmi
  • 我有那个红色背景只是为了区分我的菜单。我希望菜单容器与 menu-list @Michael Bebnjamin 成比例扩展
  • 知道了。使顶级包装器成为弹性容器。在.menu 上禁用收缩。 jsfiddle.net/kuq8L57f@ShankarRegmi
【解决方案2】:

答案就是t1m0n所说的。使用 display: inline-flex 而不是 display: flex 作为父级。

.wrapper {
  background-color: yellowgreen;
  display: block;
  padding: 10px;
  max-width: 180px;
}
.parent {
  display: inline-flex; /* -- only change --*/
  flex-flow: row nowrap;
  background-color: yellow;
}
.child {
  display: block;
  background-color: orange;
  margin: 10px;
  min-width: 50px;
}
<div class="wrapper">
  <div class="parent">
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
    <div class="child">Content</div>
  </div>
</div>

【讨论】:

  • 我没有看到与 OP 示例有任何视觉差异
猜你喜欢
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
相关资源
最近更新 更多