提问者:小点点

无法将表单输入字段移动到中心[重复]


我正在尝试建立一个小的ToDo应用程序。我试图将input字段和提交按钮放在中间,但对齐方向是左侧。

null

#todo {
  align-items: center;
  text-align: center;
}

#todo .form-group {
  align-items: center;
  margin: auto;
}

#id-button {
  margin: 10px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
<div id="todo">
  <p>
    <h3>Add New ToDo</h3>
    <div class="form-group">
      <div class="col-xs-4">
        <input type="text" class="form-control" placeholder="Add New ToDo Item">
        <button id="id-button" type="submit" class="btn btn-primary">Submit</button>
      </div>
    </div>
</div>

null

JsFiddle

有什么建议吗?


共3个答案

匿名用户

您可以这样做:

当您寻找内容居中时,CSS有一个名为flex的漂亮类和一个名为justify-content:center;的属性来处理对齐。

更多关于Justify-content的信息

添加以下内容:

#todo .form-group {
 display: flex;
 margin: 0 auto;     
 justify-content: center;
}

null

#todo {
  align-items: center;
  text-align: center;
}

#todo .form-group {
  display: flex;
  margin: 0 auto;
  justify-content: center;
}

#id-button {
  margin: 10px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<div id="todo">
  <p>
    <h3>
      Add New ToDo
    </h3>
    <div class="form-group">
      <div class="col-xs-4">
        <input type="text" class="form-control" placeholder="Add New ToDo Item">
        <button id="id-button" type="submit" class="btn btn-primary">
            Submit
            </button>
      </div>
    </div>
</div>

匿名用户

您可以将.form-group的css修改为下面的用户正确指向的css。Justify-content是解决这一问题的正确方法。

#todo .form-group {
  display: flex;
  margin: 0 auto;
  width: 100%;
  justify-content: center;
}

但是由于您使用bootstrap作为css框架。还可以在的开头添加

作为第一个子项。参考引导文件了解网格结构。引导文档

匿名用户

form {
    margin-left: 25%;
    margin-right:25%;
    width: 50%;
}     

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js">
<div id="todo">
  <p>
    <h3>Add New ToDo</h3>
    <div class="form-group">
      <div class="col-xs-4">
       <form>
        <input type="text" class="form-control" placeholder="Add New ToDo Item">
        <button id="id-button" type="submit" class="btn btn-primary">Submit</button>
       </form>
      </div>
    </div>
</div>