如何在网页中心对齐引导程序表单

时间:2017-09-24 21:42:52

标签: html css twitter-bootstrap-3

我正在使用bootstrap样式表单。我希望此表单显示在页面的中心,但即使我尝试margin 0 auto in css,我也无法执行此操作。谁能帮忙。

这是代码:

<!doctype html>
<html>
<body>
  <h2>Form</h2>
  <br>
  <form class="form-horizontal inputForm">
    <div class="form-group">
      <label class="control-label col-sm-2" for="name">Name &nbsp</label>
      <div class="col-sm-2">
        <input class="form-control" type="text">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Email &nbsp</label>
      <div class="col-sm-2">
        <input class="form-control" type="email">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button class="btn btn-primary">Sign Up</button>
      </div>
    </div>
  </form>

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link href="styles.css" rel="stylesheet">
</body>

</html>

显示上述表单的浏览器屏幕截图:

  

enter image description here

2 个答案:

答案 0 :(得分:1)

如果您不想居中body,请将表单放在div中并将该div放在中心。

&#13;
&#13;
body { text-align: center; border: 1px solid;}
form { margin: auto; width: 200px; border: solid blue; display: block;}
&#13;
<!doctype html>
<html>
<body>
  <h2>Form</h2>
  <br>
  <form class="form-horizontal inputForm">
    <div class="form-group">
      <label class="control-label col-sm-2" for="name">Name &nbsp</label>
      <div class="col-sm-2">
        <input class="form-control" type="text">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Email &nbsp</label>
      <div class="col-sm-2">
        <input class="form-control" type="email">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button class="btn btn-primary">Sign Up</button>
      </div>
    </div>
  </form>

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link href="styles.css" rel="stylesheet">
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个。我用

包裹了表格
<div class="container">
  <div class="row">
    <div class="col-md-4 mx-auto"></div>
  </div>
</div>

.mx-auto自动使列居中,在列中,您可以添加具有.col-3和col-9的表单,在我的示例中。但请根据您需要的标签和输入进行调整。

这是CodePen

修改:我已经意识到您正在使用Bootstrap 3,而不是4.在这种情况下,您可以尝试这样的事情,但它需要在移动设备上做一些工作。 CodePen