css - 输入不尊重 flex 容器宽度

标签 css flexbox

我在 Chrome 的 flex 容器中有一个 input ,除非我添加一个 min-width: 0 ,否则它不考虑容器的宽度。这似乎在 IE 中正常工作。

这里发生了什么?

.input-with-button {
  display: flex;
  width: 100px;
  border: 5px solid blue;
  margin-bottom: 10px;
}

.input-with-button input {
  flex-basis: 100%;
}
<div class='input-with-button'>
  <div>Test</div>
</div>

<div class='input-with-button'>
  <input>
</div>

最佳答案

它在 IE 中工作的原因是因为它选择了 flex-basis: 100% ,但它不应该。

它在 Chrome 中溢出的原因(并且应该在 IE 中)是因为它的 min-width 设置为 auto ,因此默认情况下 flex 元素不能小于其内容,并且在这种情况下 form 元素,例如 input ,具有默认值宽度设置使用浏览器构建它的样式表。
min-width: 0 工作的原因是,当设置为 0 时,flex 元素将,因为它的 flex-shrink 值是 1(默认值),允许收缩,并调整到其父项的宽度。

堆栈片段

.input-with-button {
  display: flex;
  width: 100px;
  border: 5px solid blue;
  margin-bottom: 10px;
}

.input-with-button input {
  flex-basis: 100%;
  min-width: 0;                        /*  added  */
}
<div class='input-with-button'>
  <div>Test</div>
</div>

<div class='input-with-button'>
  <input>
</div>



作为旁注,正如其他答案中所提到的,更改元素的默认宽度当然也是一种选择,无论它是否是 form 元素。

堆栈片段

.input-with-button {
  display: flex;
  width: 100px;
  border: 5px solid blue;
  margin-bottom: 10px;
}

.input-with-button input {
  /*flex-basis: 100%;                     removed  */
  width: 100%;                        /*  added  */
}
<div class='input-with-button'>
  <div>Test</div>
</div>

<div class='input-with-button'>
  <input>
</div>

关于css - 输入不尊重 flex 容器宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48776966/

相关文章:

javascript - 按住空格键时自定义 CSS 光标消失

html - 减少 HTML(样式)/CSS 代码(背景大小 :. .. 在背景 :. ..)

html - 无法使用 CSS 将图像扩展到浏览器高度的 100%

html - 使一个 flex item 固定宽度并且它的 sibling 都相等大小

html - 垂直对齐拉伸(stretch)的 flexbox 元素

jquery - 如何保证一定宽度的文本行不换行?

css - 简单的 CSS 字体问题

html - CSS:100% div 在移动设备上未显示为 100%

html - 创建一组内联 div,这些 div 扩展它们的宽度以填充它们的父级 - 但当达到它们的最小宽度时它们也会中断以形成新行

html - flexbox 和屏幕尺寸的问题