为什么使用flex box无法将表单输入项按垂直列方向排列
问题原因
- 你定义的
.wrapperflex相关样式没有对应生效的DOM元素:你的HTML结构里没有任何带wrapper类的容器包裹表单输入项,flex配置自然不会作用到输入元素上。 - 所有输入项、提交按钮都设置了
position: absolute:绝对定位会让元素脱离正常文档流,父级的flex布局完全无法控制这类脱离流的元素,这是你所有元素堆叠在一起的核心原因。 - flex默认是水平排列,就算容器加了flex配置,要实现垂直排列还需要额外设置
flex-direction: column属性。
修复方案
调整CSS
保留原有背景、输入框样式、占位符样式不变,做以下修改:
/* 新增/调整wrapper样式,把原来加在单个元素上的绝对定位挪到容器上 */ .wrapper { display: flex; flex-direction: column; gap: 10px; /* 控制输入项之间的间距,可自行调整数值 */ position: absolute; bottom: 84%; left: 13%; width: 12%; } /* 去掉所有.fname、.lname、.sub、.bottom-left等类里的position: absolute属性,其余原有样式保留 */ .bottom-left { font-size: 150%; color: white; background-color: black; font: Georgia; margin-bottom: 8px; }
调整HTML
把label挪到form内部,给form加上wrapper类,同时修正所有输入项name重复的bug(原有所有输入项的name都是fname,提交时数据会被覆盖):
<title>task Page</title> </head> <body> {%if msg%} <p>{{msg}}</p> {%endif%} <form name="tasks" action="/add-tasks" method="POST" class="wrapper"> <label class="bottom-left" for="fname">First name</label> <input class="fname" type="text" id="fname" name="fname" placeholder="FIRST NAME"> <input class="lname" type="text" id="lname" name="lname" placeholder="LAST NAME"> <input class="add1" type="text" id="add1" name="add1" placeholder="address 1"> <input class="add2" type="text" id="add2" name="add2" placeholder="address 2"> <input class="postal" type="text" id="postal" name="postal" placeholder="postal code"> <input class="country" type="text" id="country" name="country" placeholder="country"> <input class="city" type="text" id="city" name="city" placeholder="city"> <input class="state" type="text" id="state" name="state" placeholder="state"> <input class="sub" type="submit" value="Submit"> </form> </body> </html>
内容的提问来源于stack exchange,提问作者user16410404
相关产品推荐
相关产品推荐

