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

如何使用Bootstrap将标题与搜索栏居中显示在屏幕中央

解决方案

问题核心原因

  1. 你当前使用的是 Bootstrap 3 版本(代码中用到了glyphicon图标类),而my-auto是 Bootstrap 4 及以上版本才新增的间距工具类,所以完全不会生效。
  2. 即便使用高版本 Bootstrap,my-auto实现垂直居中的前提是父容器拥有明确的高度,默认状态下父元素高度由内容撑开,没有多余空间供margin自动分配,自然无法实现垂直居中。

适配 Bootstrap 3 的修改方案(无需升级版本)

只需要修改少量代码即可实现标题和搜索栏全屏垂直+水平居中:

  1. 给<body>添加内联样式,让页面占满全屏高度,使用flex布局实现垂直居中
  2. 移除.container上的固定margin-top:8%,避免不同分辨率下位置偏移
  3. 调整搜索图标位置,放到<button>标签内部避免显示错位

修改后完整代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="stylesheet.css" rel="stylesheet">
    
  </head>
  <!-- 新增body的样式 -->
  <body style="min-height: 100vh; display: flex; align-items: center; margin: 0;">
   <div class="container">
       <div class="col-md-6 col-md-offset-3">     
        <div class="row">
              <div id="logo" class="text-center">
                <h1>Movie</h1>
              </div>
           <form role="form" id="form-buscar">
             <div class="form-group">
               <div class="input-group">
                 <input id="1" class="form-control" type="text" name="search" placeholder="Search..." required/>
                 <span class="input-group-btn">
                   <button type="button" class="btn btn-outline-primary">
                     search
                     <!-- 图标移到按钮内部 -->
                     <i class="glyphicon glyphicon-search" aria-hidden="true"></i>
                   </button>
                 </span>
               </div>
             </div>
          </form>
         </div>            
       </div>
       <p class="text-center">movie!</p>
    </div>
      
      
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

如果升级到 Bootstrap 4/5 的简化方案

高版本 Bootstrap 内置了工具类,无需写自定义内联样式:

  • 给<body>添加class="d-flex min-vh-100 align-items-center"即可实现垂直居中逻辑
  • 内容水平居中可以直接用mx-auto类替代原来的col-md-offset-3
  • 此时如果需要调整垂直方向的间距,my-auto类就可以正常生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:54:00