如何实现表单中文本输入框与提交按钮同行显示?
让文本输入框和提交按钮在同一行显示的解决方案
嘿,我看你想让搜索输入框和提交按钮并排显示,咱们调整下代码结构就能搞定啦!
你的原代码已经用到了Bootstrap的样式类,但input-group的嵌套逻辑有点问题——这个组件是用来直接包裹输入框和附加按钮的,而不是把整个表单包进去。这里有两个简单好用的修复方案:
方案1:利用Bootstrap的Input Group组件(推荐)
这个方案贴合Bootstrap的组件设计,能完美实现输入框和按钮横向排列:
<form action="searchresult.php" method="post"> <div class="input-group"> <input type="text" name="searchtext" class="form-control" placeholder="Search"> <button class="btn btn-secondary" type="submit"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z"/> <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z"/> </svg> </button> </div> </form>
为什么这么改:
把input-group放在表单内部,直接包裹输入框和按钮——Bootstrap的input-group会自动用flex布局让内部元素横向排列,不需要额外写自定义样式。
方案2:用Flex布局直接控制表单
如果不想依赖input-group组件,也可以给表单加flex类来实现并排效果:
<form action="searchresult.php" method="post" class="d-flex"> <input type="text" name="searchtext" class="form-control me-2" placeholder="Search"> <button class="btn btn-secondary" type="submit"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-search" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M10.442 10.442a1 1 0 0 1 1.415 0l3.85 3.85a1 1 0 0 1-1.414 1.415l-3.85-3.85a1 1 0 0 1 0-1.415z"/> <path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zM13 6.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0z"/> </svg> </button> </form>
说明:
d-flex让表单变成flex容器,内部元素会自动横向排列me-2给输入框添加了右侧间距(如果用Bootstrap 4,换成mr-2即可),避免按钮和输入框挤在一起
两种方案都能轻松实现你要的“同一行显示”效果,选哪个全看你的需求偏好啦!
内容的提问来源于stack exchange,提问作者nomela
相关产品推荐
相关产品推荐

