You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Bootstrap实现表单与按钮的水平居中?

解决Bootstrap表单与按钮无法居中的问题

嘿,我瞅了下你的代码和效果,问题主要出在表单结构不规范和Bootstrap布局类的使用不到位上,咱们一步步来把它搞定:

问题分析

  1. 你的提交按钮放在了<form>标签外面,这既不符合表单的标准结构,也没法让表单和按钮统一受布局控制;
  2. 表单所在的.col没有添加居中相关的工具类,再加上自定义的.icon设置了max-width:25%,但没让这个容器自身居中;
  3. 你自定义的body和html高度样式,其实可以用Bootstrap自带的工具类简化,避免冗余。

修改后的代码

CSS 代码

body { 
  background-color: whitesmoke; 
  min-height: 100vh; /* 用min-vh-100更贴合全屏居中需求 */
  display: flex; 
  align-items: center; 
}
.random { text-decoration: none; margin-bottom: 50px; }
.icon { 
  max-width: 25%; 
  margin: 0 auto; /* 让表单容器自身水平居中 */
}

HTML 代码

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="container">
  <div class="row justify-content-center"> <!-- 让整行内容水平居中 -->
    <div class="col-auto"> <!-- 用col-auto自适应宽度,避免占满整行 -->
      <a href="https://en.wikipedia.org/wiki/Special:Random" target="_blank" class="btn btn-primary random">
        Click here for a random article
      </a>
    </div>
  </div>
  <div class="row justify-content-center"> <!-- 整行内容居中 -->
    <form class="icon">
      <div class="input-group"> <!-- 用input-group整合输入框和按钮,保证布局统一 -->
        <input type="text" class="form-control">
        <div class="input-group-append">
          <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button>
        </div>
      </div>
    </form>
  </div>
  <div class="row justify-content-center mt-3"> <!-- 加margin-top和表单拉开距离 -->
    <div class="col-auto">
      Click icon to search
    </div>
  </div>
</div>

修改说明

  • 把提交按钮移入<form>内,并用Bootstrap的input-group组件整合输入框和按钮,既符合表单规范,又能统一控制布局;
  • 给所有需要居中的行添加justify-content-center类,让行内内容水平居中;
  • 给表单容器.icon加上margin:0 auto,确保它在父容器中水平居中;
  • 补充了Font Awesome的CSS链接,避免搜索图标无法显示;
  • 调整了随机文章按钮的嵌套结构,把a标签直接作为按钮载体,避免样式冲突。

这样修改后,你的表单、按钮和其他元素就能一起完美居中啦~

内容的提问来源于stack exchange,提问作者sinan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:09:18