我有form
个input
标记位于div
内。我试图让form
/ input
尊重父级的宽度,但我似乎无法让它对flexbox做出反应 - 它只是决定自己的宽度并溢出容器。
HTML
<div class="container">
<span>foo</span>
<span>bar</span>
<form>
<input value="baz"/>
</form>
</div>
CSS
.container {
display: flex;
width: 150px;
border: 1px solid black;
}
截图
我期望的是父div上的flexbox设置会缩小表单以适应其宽度,但这不会发生。相反,即使我在其上设置了form
,input
/ flex-shrink
也只是处于所需的宽度而不会缩小。
答案 0 :(得分:2)
如果您添加此规则,input
将会调整。
.container input {
width: 100%; /* override its defalt width */
box-sizing: border-box; /* make border/padding size be
included in the set width */
}
.container {
display: flex;
width: 150px;
border: 1px solid black;
}
.container input {
width: 100%; /* override its defalt width */
box-sizing: border-box; /* make border/padding size be
included in the set width */
}
<div class="container">
<span>foo</span>
<span>bar</span>
<form>
<input value="baz" />
</form>
</div>
原因是,flex项目(此处为form
)不能小于其内容,即使允许其使用flex-shrink
缩小。
在这种情况下,它是input
,它具有预定义的宽度,因此强制form
与其一起调整大小,其中解决方案是覆盖input
的宽度。
此外,由于input
不是弹性项目,form
是,它不会响应弹性项目属性。
Flex容器/ flex项目具有父/子关系,并且只有子项是flex项目,而不是孙子项目。
以下是关于flex容器/项目和表单元素的更多内容:
答案 1 :(得分:1)
试试这个
.container {
display: flex;
width: 150px;
border: 1px solid black;
}
form input{
width: 100%;
box-sizing: border-box;
}
<div class="container">
<span>foo</span>
<span>bar</span>
<form>
<input value="baz">
</form>
</div>