把按钮放在div的中心

时间:2017-07-15 08:54:36

标签: css flexbox alignment

我想在div的中心放置一个按钮(垂直和水平)。

此处:CSS: center element within a <div> element

批准的答案说这段代码:

#button_div {
  display: flex;
  align-items: center;
  justify-content: center;
}

会实现这一目标。应用此代码时,按钮垂直输入,但不是水平输入。相反,它位于div的右边缘。

我的HTML代码是这样的:

<div class="col-md-1" id="button_div"></div>

按钮动态创建如下:

closeButton = document.createElement("BUTTON");
var text = document.createTextNode("remove");
closeButton.className = "btn btn-danger";
closeButton.setAttribute("style", "margin: auto;");

closeButton.appendChild(text);                                      

$("#button_div").append(closeButton);

如何将按钮水平居中?

2 个答案:

答案 0 :(得分:0)

  

检查下面的代码段。它的工作。

&#13;
&#13;
  

  closeButton = document.createElement("BUTTON");
    var text = document.createTextNode("remove");
    closeButton.className = "btn btn-danger";
    /* closeButton.setAttribute("style", "margin: auto;"); */

    closeButton.appendChild(text);                                      

    $("#button_div").append(closeButton);
&#13;
   

 #button_div  {
                    display:-webkit-flex;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    text-align:center /*add this*/
            
                }
             .btn{
                  display:inline-block
                }
                
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-md-1" id="button_div">

</div>
&#13;
&#13;
&#13;

  #button_div  {
            display:-webkit-flex;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align:center /*add this*/

        }
     .btn{
          display:inline-block
        }

答案 1 :(得分:0)

似乎工作正常。你不需要按钮的margin:auto

&#13;
&#13;
closeButton = document.createElement("BUTTON");
var text = document.createTextNode("remove");
closeButton.className = "btn btn-danger";
/* closeButton.setAttribute("style", "margin: auto;"); */

closeButton.appendChild(text);                                      

$("#button_div").append(closeButton);
&#13;
#button_div {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  background-color: lightblue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-md-1" id="button_div"></div>
&#13;
&#13;
&#13;