0

I want to put a button at the center of a div (both vertically and horizontally).

Here: CSS: center element within a <div> element

the approved answer says that this code:

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

would achieve this. Applying this code, the button is entered vertically but not horizontally. Instead it is positioned at the right edge of the div.

My html code is this:

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

The button is dynamically created as follows:

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);

How can I center the button horizontally as well?

steady_progress
  • 3,311
  • 10
  • 31
  • 62

2 Answers2

0

check snippet below. its working.

  

  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);
   

 #button_div  {
                    display:-webkit-flex;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    text-align:center /*add this*/
            
                }
             .btn{
                  display:inline-block
                }
                
<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>
  #button_div  {
            display:-webkit-flex;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align:center /*add this*/

        }
     .btn{
          display:inline-block
        }
0

Seems to work fine. You don't need the margin:auto for the button.

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);
#button_div {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  background-color: lightblue;
}
<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>
Gerard
  • 15,418
  • 5
  • 30
  • 52