CSS flexbox 换行未调整大小以适应内容

Ago*_*ony 5 html css flexbox

显示问题的简化 plunkr: https://plnkr.co/edit/mHTHLEumQ04tInFVAz3z ?p=preview

如果调整右视口的大小直到两个容器不再适合同一行,则右视口将移动到新行。

然而,父级 inline-flex 容器的宽度不会改变,顶部的“header”元素会被抛出——“header”中的“button”应该与下面容器中的最后一个项目右对齐。

两个(或多个)项目具有固定宽度,但它们之间没有空间。这些是唯一具有固定宽度或高度的元素。

当项目换行到新行时,如何强制 Flex 容器宽度适应/收缩(不使用 js,纯 HTML/CSS)?

.main-flex {
  display: -webkit-inline-flex;
  display: inline-flex;
  -webkit-flex-direction: column;
  flex-direction: column;
}

.flex-container {
  flex-grow: 1;
  display: -webkit-inline-flex;
  display: inline-flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  flex-wrap: wrap;
}
Run Code Online (Sandbox Code Playgroud)
<div style="margin-top: 100px;" class="main-flex">
  <div>
    <span>header</span>
    <span style="float:right">button</span>
  </div>
  <div class="flex-container">
    <div style="height: 400px; width:250px; border: 1px solid black;"></div>
    <div style="height: 400px; width:250px; border: 1px solid black;"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 2

In CSS, the parent container doesn't know when its children wrap. Hence, it continues scaling its size oblivious to what's going on inside.

Put another way, the browser renders the container on the initial cascade. It doesn't reflow the document when a child wraps.

That's why the container doesn't shrink-wrap the narrower layout. It just continues on as if nothing wrapped, as evidenced by the reserved space on the right.

More details here: Make container shrink-to-fit child elements as they wrap


但您不需要缩小容器即可使布局正常工作。只需对 HTML 和 CSS 进行一些调整即可构建它。

.main-flex {
  display: inline-flex;
  flex-wrap: wrap;
}

.flex-container {
  display: flex;
  flex-direction: column;
}

.flex-container>div {
  height: 400px;
  width: 250px;
  border: 1px solid black;
}

.flex-container:nth-child(2)>span {
  align-self: flex-end;
}
Run Code Online (Sandbox Code Playgroud)
<div class="main-flex">
  <div class="flex-container">
    <span>header</span>
    <div></div>
  </div>
  <div class="flex-container">
    <span>button</span>
    <div></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

修改后的演示