Html 强制 flex 项目跨越整个行宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48101046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:02:41  来源:igfitidea点击:

Force flex item to span full row width

htmlcssflexbox

提问by MPaul

I'm trying to retain the first 2 child elements on the same row while the third element is in its own below at full width, all while using flex.

我试图将前 2 个子元素保留在同一行上,而第三个元素在其下方以全宽显示,所有这些都使用 flex。

I'm particularly interested in using the flex-growand flex-shrinkproperties on the first 2 elements (which is one of my reasons for not using percentages) however the third element really must be full width and below the first two.

我对在前 2 个元素上使用flex-growflex-shrink属性特别感兴趣(这是我不使用百分比的原因之一),但是第三个元素确实必须是全宽并且低于前两个元素。

The labelelement is added programmatically after the textelement when there's an error and I can't change the code.

当出现错误并且我无法更改代码时,该label元素以编程方式添加到text元素之后。

How do I force the label element to span a 100% width below the other two elements which are positioned using flex?

如何强制标签元素在使用 flex 定位的其他两个元素下方跨越 100% 的宽度?

.parent {
  display: flex;
  align-items: center;
  width: 100%;
  background-color: #ececec;
}

.parent * {
  width: 100%;
}

.parent #text {
  min-width: 75px;
  flex-shrink: 2.25;
}
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message</label>
</div>

回答by Michael Benjamin

Whenever you want a flex item to occupy an entire row, set it to width: 100%/ flex-basis: 100%, and enable wrapon the container.

每当您想要一个 flex 项目占据整行时,请将其设置为width: 100%/ flex-basis: 100%,并wrap在容器上启用。

The item now consumes all available space. Siblings are forced on to other rows.

该项目现在消耗所有可用空间。兄弟姐妹被迫转到其他行。

.parent {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background-color: #ececec;
}

.error {
  flex: 0 0 100%; /* fg: 0, fs: 0, fb: 100% */
  border: 1px dashed red;
}

#range, #text {
  flex: 1;
}
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message</label>
</div>

回答by tao

You appear to be looking for min-widthon child and flex-wrap:wrapon parent:

您似乎正在寻找min-width孩子和flex-wrap:wrap父母:

.parent {
   display: flex;
   align-items: center;
   flex-wrap: wrap;
}

.parent > * {
  flex-grow: 1;
}

.parent > .error {
  min-width: 100%;
  background-color: rgba(255,0,0,.3);
}
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message</label>
</div>