CSS flexbox wrap not resizing to fit contents [duplicate]

﹥>﹥吖頭↗ 提交于 2020-01-13 14:57:28

问题


A simplified plunkr to show the problem: https://plnkr.co/edit/mHTHLEumQ04tInFVAz3z?p=preview

If you resize the right viewport until the two containers no longer fit on the same row, right one moves to a new line.

However the parent inline-flex container width does not change, throwing the top "header" element off - the "button" in "header" should be right aligned with the last item in the container below.

The two (or more) items have fixed width but no space between them. Those are the only elements with fixed width or height.

How can I force the flex container width to fit/shrink when items wrap to a new row (without using js, pure 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;
}
<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>

回答1:


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


But you don't need the container to shrink for your layout to work. It can be built with a few adjustments to your HTML and 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;
}
<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>

revised demo



来源:https://stackoverflow.com/questions/43908072/css-flexbox-wrap-not-resizing-to-fit-contents

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