我正在实现一个表单,该表单包含多个具有不同数量输入字段的部分。当在父 div 上使用 display:flex
并在输入字段上使用 100% 宽度时,我会计算出不同的宽度,具体取决于表单内输入字段的数量。
当使用 display: block
时,一切都按预期工作。
<section>
One input field.
<div>
<form action="">
<input type="text">
</form>
</div>
</section>
<section>
Two input fields.
<div>
<form action="">
<input type="text"> <!-- each input field is double as wide as in the first section! -->
<input type="text">
</form>
</div>
</section>
section {
background: lightgrey;
width: 1100px;
}
div {
background: red;
display: flex;
}
form {
background: blue;
box-sizing: border-box;
}
input {
box-sizing: border-box;
width: 100%;
margin: 0.3125em 0 0.625em;
}
这应该是正常的 flexbox 行为吗?我错过了什么吗? 感谢您的帮助!
最佳答案
只需删除 width:100%
你会更好地理解:
section {
background: lightgrey;
width: 1000px;
}
div {
background: red;
display: flex;
}
form {
background: blue;
box-sizing: border-box;
}
input {
box-sizing: border-box;
margin: 0.3125em 0 0.625em;
}
<section>
One input field.
<div>
<form action="">
<input type="text">
</form>
</div>
</section>
<section>
Two input fields.
<div>
<form action="">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
Three input fields.
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
Four input fields.
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
输入定义了蓝色框的宽度,然后这个宽度将作为 width: 100%;
的引用。使所有输入成为它的全宽。
基本上,百分比值需要引用,因此首先根据内容计算蓝色框的宽度,然后输入将使用该宽度作为引用。
这也可能发生在简单的内联 block 元素上
section {
background: lightgrey;
width: 1000px;
}
div {
background: red;
display: inline-block;
}
form {
background: blue;
box-sizing: border-box;
}
input {
box-sizing: border-box;
width:100%;
margin: 0.3125em 0 0.625em;
}
<section>
<div>
<form action="">
<input type="text">
</form>
</div>
</section>
<section>
<div>
<form action="">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
<section>
<div>
<form action="">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
</form>
</div>
</section>
有关百分比调整的更多详细信息,请点击此处:https://www.w3.org/TR/css-sizing-3/#percentage-sizing
您可以找到此类行为的明确示例:
For example, in the following markup:
<article style="width: min-content">
<aside style="width: 50%;">
LOOOOOOOOOOOOOOOOOOOONG
</aside>
</article>
When calculating the width of the outer
<article>
, the inner<aside>
behaves aswidth: auto
, so the<article>
sets itself to the width of the long word. Since the<article>
’s width didn’t depend on "real" layout, though, it’s treated as definite for resolving the<aside>
, whose width resolves to half that of the<article>
.
When using display: block, everything works as intended.
仅仅是因为 block 元素的宽度计算是不同的,并且不依赖于内容,这与内容定义宽度的内联 block 元素或 flex 元素不同
关于html - 为什么输入字段宽度会随着输入数量(flexbox)的增加而增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56792757/